美文网首页
Identical Binary Tree

Identical Binary Tree

作者: 一枚煎餅 | 来源:发表于2016-09-19 04:06 被阅读0次
Identical Binary Tree.png

解題思路 :

單純檢查兩棵樹的每一個點 透過起點再去 recursive call 檢查左跟右的子節點 一旦發現不同就直接回報 false 了

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 identical, or false.
/
bool isIdentical(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 (isIdentical(a->left, b->left) && isIdentical(a->right, b->right));
}
};

相关文章

网友评论

      本文标题:Identical Binary Tree

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