Given two binary trees, write a function to check if they areequal or not.
Two binary trees are considered equal if they are structurallyidentical and the nodes have the same value.
给定两个二叉树,写一个函数来检查它们是否是相等或不相等。
如果两个二叉树在结构上相同且节点具有相同的值,则它们被认为是相等的。
代码实现如下:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p == NULL && q == NULL)
return true;
if ((p == NULL && q != NULL) || (p != NULL && q == NULL))
return false;
if (p->val != q->val)
return false;
bool left = isSameTree(p->left, q->left);
bool right = isSameTree(p->right, q->right);
return left && right;
}