Identical Binary Tree

Identical Binary Tree_第1张图片
Identical Binary Tree.png

解題思路 :

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

C++ 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)