100.Same Tree

很简单的二叉树遍历问题,递归定义:两颗树相等=根相等+左子树相等+右子树相等。特殊处理根为空的情况,很容易写出递归的实现。

非递归的话深度遍历使用栈,层次遍历使用队列。

 1 /**
 2 
 3  *Definition for a binary tree node.
 4 
 5  *struct TreeNode {
 6 
 7  *    int val;
 8 
 9  *    TreeNode *left;
10 
11  *    TreeNode *right;
12 
13  *    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
14 
15  *};
16 
17  */
18 
19 class Solution {
20 
21 public:
22 
23        boolisSameTree(TreeNode* p, TreeNode* q) {
24 
25               if(!p&&!q)
26 
27                      return1;
28 
29               elseif (p&&q)
30 
31               {
32 
33                      if(p->val != q->val)
34 
35                             return0;
36 
37                      else
38 
39                        returnisSameTree(p->left, q->left) && isSameTree(p->right,q->right);
40 
41  
42 
43               }
44 
45               else
46 
47                      return0;
48 
49        }
50 
51 };

 

posted @ 2016-11-21 17:16  Initial_Dream  阅读(138)  评论(0)    收藏  举报