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.
思路:这道题很明显用递归来实现,但是退栈的判断条件需要好好考虑
1.p->val !=q->val 这是值不等的情况,毫无疑问要return false 来退栈
2.还有就是二叉树结构的不相同的情况,递归下去就是发现q==null but p!=null
3.一直递归到叶子下一层,那么肯定是p=q=null
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p==NULL && q ==NULL)
return true;
if (p==NULL || q ==NULL)
return false;
if (p->val != q->val)
return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right) ;
}
};