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.

 

Analyse: Compare all nodes in the same place.

1. Recursion

    Runtime: 0ms.

 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 && !q) return true;
14         if(!p || !q) return false; //the first line eliminated the situation s.t. both trees are null
15         return p->val == q->val &&
16                isSameTree(p->left, q->left) &&
17                isSameTree(p->right, q->right);
18     }
19 };

 

2. Iteration with stack used

    Runtime: 0ms.

 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         stack<TreeNode* > stk;
14         stk.push(p);
15         stk.push(q);
16         
17         while(!stk.empty()){
18             p = stk.top();
19             stk.pop();
20             q = stk.top();
21             stk.pop();
22             
23             if(!p && !q) continue;
24             if(!p || !q) return false;
25             if(p->val != q->val) return false;
26             
27             stk.push(p->left);
28             stk.push(q->left);
29             stk.push(p->right);
30             stk.push(q->right);
31         }
32         return true;
33     }
34 };

 

3. Iteration with queue used

    Runtime: 4ms.

 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         queue<TreeNode* > qu;
14         qu.push(p);
15         qu.push(q);
16         
17         while(!qu.empty()){
18             p = qu.front();
19             qu.pop();
20             q = qu.front();
21             qu.pop();
22             
23             if(!p && !q) continue;
24             if(!p || !q) return false;
25             if(p->val != q->val) return false;
26             
27             qu.push(p->left);
28             qu.push(q->left);
29             qu.push(p->right);
30             qu.push(q->right);
31         }
32         return true;
33     }
34 };

 

posted @ 2015-07-28 13:07  amazingzoe  阅读(115)  评论(0编辑  收藏  举报