100. Same Tree

1. 问题描述

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

Tags: Tree Depth-first Search
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

2. 解题思路


3. 代码

 1 class Solution {
 2 public:
 3     bool isSameTree(TreeNode* p, TreeNode* q)
 4     {
 5         if (NULL == p && NULL == q)
 6         {
 7             return true;
 8         }
 9 
10         if (NULL != p && NULL != q)
11         {
12             if (p->val == q->val)
13             {
14                 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
15             }
16             else
17             {
18                 return false;
19             }
20         }
21         return false;
22     }
23 #pragma region 非递归方式
24     bool isSameTree_1(TreeNode *p, TreeNode *q) 
25     {
26         if(!isSameNode(p, q))
27             return false;
28         if(!p && !q)
29             return true;
30 
31         queue<TreeNode*> lqueue;
32         queue<TreeNode*> rqueue;
33         lqueue.push(p);
34         rqueue.push(q);
35         while(!lqueue.empty() && !rqueue.empty())
36         {
37             TreeNode* lfront = lqueue.front();
38             TreeNode* rfront = rqueue.front();
39 
40             lqueue.pop();
41             rqueue.pop();
42 
43             if(!isSameNode(lfront->left, rfront->left))
44                 return false;
45             if(lfront->left && rfront->left)
46             {
47                 lqueue.push(lfront->left);
48                 rqueue.push(rfront->left);
49             }
50 
51             if(!isSameNode(lfront->right, rfront->right))
52                 return false;
53             if(lfront->right && rfront->right)
54             {
55                 lqueue.push(lfront->right);
56                 rqueue.push(rfront->right);
57             }
58         }
59         return true;
60     }
61     bool isSameNode(TreeNode* p, TreeNode *q)
62     {
63         if(!p && !q)
64             return true;
65         if((p && !q) || (!p && q) || (p->val != q->val))
66             return false;
67         return true;
68     }
69 #pragma endregion
70 };

4. 反思

posted on 2016-06-26 22:13  whl-hl  阅读(150)  评论(0编辑  收藏  举报

导航