Tweaked Identical Binary Tree

2016-09-19  本文已影响0人  一枚煎餅
Tweaked Identical Binary Tree -1.png
Tweaked Identical Binary Tree -2.png

解題思路 :

題目有個小陷阱 注意這句 Assuming any number of tweaks are allowed.
可以扭轉偶數的次數 那這棵樹或是子樹就會變成跟原本一樣 所以在檢查的時候 除了檢查是否為對稱的樹 也要同時檢查是否為同樣的樹

C++ code :

<pre><code>
/**

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);
}
};

上一篇 下一篇

猜你喜欢

热点阅读