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.
void traverse(struct TreeNode* p, struct TreeNode* q, bool *f)
{
if (!*f)
return;
if (p == NULL&&q != NULL || p != NULL&&q == NULL)
{
*f = false;
return;
}
if (p != NULL&&q != NULL)
{
if (p->val != q->val)
{
*f = false;
return;
}
traverse(p->left, q->left,f);
traverse(p->right, q->right,f);
}
return;
}
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
bool f = true;
traverse(p, q, &f);
return f;
}accept

本文介绍了一种检查两棵二叉树是否等价的方法。等价是指这两棵树不仅结构相同,而且每个对应节点的值也完全一样。通过递归遍历的方式比较两棵树的节点值来实现这一功能。

被折叠的 条评论
为什么被折叠?



