100. Same Tree
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
题目要判断两个二叉树是否相同,并说明了要求,只要结构相同并节点有相同的值。先说一般的情况,输入的两节点都不为空,且值相同,则可以继续判断两者左右子节点是否相同,这里使用递归的方式比较直观。而递归的边界则有两节点都为空,此时即可返回true,另一边界则是上面一般情况的反面,两节点不为空或其一为空,或值不同,或左右子节点有不同,这里要写条件判断就比较麻烦了,所以可以不用写到if或者else if中,归入else就好。具体代码如下:
/**
* 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 && q) {
if (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) {
return true;
}
else {
return false;
}
}
else if (!p && !q) {
return true;
}
else {
return false;
}
}