题目
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.
分析
比较两个二叉树是否相等,依次判断根节点和左右子数是否相同,使用递归即可,可能递归带来的函数调用花费时间较多一些,但是所有节点只判断了一次。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool sameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL)
{
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 false;
return sameTree(p->left,q->left)&&sameTree(p->right,q->right);
}
else
return false;
}
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
return sameTree(p,q);
}