您的位置:首页 > 其它

leetcode Same Tree

2015-11-11 15:59 423 查看
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

做这道题的时候犯了两个错误,(1)刚开始的竟然直接用p==q,p和q是指针,只要指的不是一块内存,应该返回的都是false啊。(2)后来*p==*q,可是并没有运算符==重载,这样也是没有结果的。

后来发现只要value值一样就可以了,事实上体现出来的就是两个节点的value值,【递归】什么的真的很好用。为以前没有好好学递归感到遗憾啊。easy程度的题的确可以一天刷好几道。应该安排的是时间不是量。因为随着能力的提高,程度不一样了,量也应该减少,减肥应该也是这样的,【吸取教训】

/**
* 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;
if(p!=NULL&&q!=NULL){
if(p->val==q->val){
if(isSameTree(p->right,q->right)&&isSameTree(p->left,q->left)) return true;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: