美文网首页
Tweaked Identical Binary Tree

Tweaked Identical Binary Tree

作者: 一枚煎餅 | 来源:发表于2016-09-19 03:10 被阅读0次
Tweaked Identical Binary Tree -1.png
Tweaked Identical Binary Tree -2.png

解題思路 :

題目有個小陷阱 注意這句 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);
}
};

相关文章

网友评论

      本文标题:Tweaked Identical Binary Tree

      本文链接:https://www.haomeiwen.com/subject/udwgettx.html