[面试真题] 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.

广度优先遍历,考察两棵树中每一个的值以及左右孩子的值是否相等。

Program Runtime: 8 milli secs

 1 /**
 2  * Definition for binary tree
 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         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if(q == p){
16             return true;
17         }
18         queue<TreeNode*> qq, qp;
19         if(NULL == p && NULL == q){
20             return true;
21         }else if(NULL != p && NULL != q){
22             qq.push(q);
23             qp.push(p);
24         }else{
25             return false;
26         }
27         while(qq.size() != 0 && qp.size() != 0){
28             TreeNode *curp = qp.front();
29             qp.pop();
30             TreeNode *curq = qq.front();
31             qq.pop();
32             if(curq->val != curp->val){
33                 return false;
34             }
35             if(curp->left && curq->left) {
36                 if(curp->left->val != curq->left->val){
37                     return false;
38                 }
39                 qp.push(curp->left);
40                 qq.push(curq->left);
41             }else if(curp->left != NULL && curq->left == NULL){
42                 return false;
43             }else if(curp->left == NULL && curq->left != NULL){
44                 return false;
45             }
46             if(curp->right && curq->right) {
47                 if(curp->right->val != curq->right->val){
48                     return false;
49                 }
50                 qp.push(curp->right);
51                 qq.push(curq->right);
52             }else if(curp->right != NULL && curq->right == NULL){
53                 return false;
54             }else if(curp->right == NULL && curq->right != NULL){
55                 return false;
56             }
57         }
58         if(qq.size() != 0 || qp.size() != 0){
59             return false;
60         }
61         return true;
62     }
63 };

 

你可能感兴趣的:(LeetCode)