Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if(NULL == p || NULL == q)
return p==q;
if(p->val!=q->val)
return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
经验教训
递归实现,if(!p || !q)判断如果其中有一个位NULL,那么去判断p ==q,如果两者都非空才能去判断val的值是否相等,然后再去判断左子树和右子树是否相等。