一、题目描述
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.
判断两棵树是否相等,即有相同的结构,同一位置的值也相等。
思路:
用递归的思想还是很容易想到和实现的。现在只看单个的节点,比如节点p和节点q,只要p为空,q为空,那么就是相等的,返回true。如果p和q的值不相等,或者p为空q非空,或者p非空q为空,那么就是不相等,返回false。该节点的情况判断完了,接下来就看它们的左孩子和右孩子就可以了,这时就用到递归了。
这里要注意一点,一开始我将判断p和q的值不相等这个条件放在最前面,老是出现runtime Error,提示[],[0]这个例子执行不对,之后将这个条件放在判断的最后就对了。可能是因为当一个节点p为空时,访问它的值p->val会出现内存泄漏导致编译报错。
c++代码(0ms)
/**
* 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==NULL) && !(q==NULL)) || ((p->val != q->val) && (p!=NULL) && (q!=NULL)))
return false;
else
return (isSameTree(p->left,q->left) && isSameTree(p->right, q->right));
}
};