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 isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p == NULL || q == NULL)
{
return (p == NULL && q == NULL) ? true : false;
}
if(p->left == NULL && p->right == NULL && q->left == NULL && q->right == NULL)
{
return (p->val == q->val) ? true : false;
}
return ((p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}