现在开始按照AC率降序刷题,接下来的这几道题目确实都是挺简单的。
题目如下:
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.
分析如下:
简单题,判断两棵树是否是一样的。递归判断。
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p==NULL&&q==NULL)
return true;
else if(p==NULL&&q!=NULL)
return false;
else if(p!=NULL&&q==NULL)
return false;
else if(p!=NULL&&q!=NULL&&p->val!=q->val)
return false;
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}
};
updated: 2014-10-06
上面的条件判断太不够简洁。判断same tree false的case比较多,但是判断same tree true的case 比较少,所以修改版以same tree true的条件为基准来写,不满足这个条件的则必然为false.
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
return (p == NULL && q == NULL) ||
((p != NULL && q != NULL && p->val == q->val) &&
(isSameTree(p->left, q->left) && isSameTree(p->right, q->right)));
}
};