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 binary tree
* 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&&!q)
return true;
if (!p || !q)
return false;
return (p->val==q->val)&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};