解題思路 :
題目有個小陷阱 注意這句 Assuming any number of tweaks are allowed.
可以扭轉偶數的次數 那這棵樹或是子樹就會變成跟原本一樣 所以在檢查的時候 除了檢查是否為對稱的樹 也要同時檢查是否為同樣的樹
C++ code :
<pre><code>
/**
- Definition of TreeNode:
- class TreeNode {
- public:
int val;
TreeNode *left, *right;
TreeNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
- }
*/
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are tweaked identical, or false.
*/
bool isTweakedIdentical(TreeNode* a, TreeNode* b) {
// Write your code here
if(!a && !b) return true;
if(!a || !b) return false;
if(a->val != b->val) return false;
return isTweakedIdentical(a->left, b->right) && isTweakedIdentical(a->right, b->left)
|| isTweakedIdentical(a->left, b->left) && isTweakedIdentical(a->right, b->right);
}
};