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.
Subscribe to see which companies asked this question
/**
* Definition for a binary tree node.
* 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 == NULL && q == NULL) {
return true;
} else if (p != NULL && q != NULL && p->val == q->val) {
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
} else {
return false;
}
}
};
本文提供了一种方法来检查两棵二叉树是否相等。如果两棵树在结构上完全相同且节点值也相同,则认为这两棵树是相等的。通过递归的方式对比两棵树的根节点、左子树和右子树来实现这一判断。
966

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



