leetcode 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

 

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

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

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSameTree(TreeNode* p, TreeNode* q) {
13         if(p==NULL&&q==NULL) return true;
14         if(p!=NULL&&q!=NULL){
15         if(p->val==q->val){
16             if(isSameTree(p->right,q->right)&&isSameTree(p->left,q->left)) return true;
17         }
18         }
19         return false;
20     }
21 };

 

posted @ 2015-11-11 15:59  0giant  阅读(182)  评论(0编辑  收藏  举报