Same Tree

The Question

Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

The Answer

没什么好说的,遍历比较就可以了。

The Key

  1. 树都为空的情况;
  2. 遍历时候,一个为空了,一个还没有的情况;
  3. 递归调用的时候,一定要有返回值。
  4. else和最近的if语句,块搭配。

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool (TreeNode* p, TreeNode* q) {
if(!p&&!q) return true;
if((!p&&q)||(!q&&p)) return false;
if(p->left==NULL&&p->right==NULL&&q->left==NULL&&q->right==NULL&&p->val==q->val)
return true;
if(p->val==q->val){
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
else return false;
}
};

~Thanks~
By 海天游草~~~2017.3.14