CoderJesse  
wangjiexi@CS.PKU
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
    1
   / \
  2   2
 / \ / \
3  4 4  3
But the following is not:
    1
   / \
  2   2
   \   \
   3    3
Note:
Bonus points if you could solve it both recursively and iteratively.

判断两个节点是否对称,只需保证,这两个点是否相等,这个点的左子节点和另一个点的有子节点是否相等,这个点的右子节点和另一个点的左子节点是否相等。
最初的两个点必须是根节点的左右子节点。

 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 key;
13     bool isSymmetric(TreeNode *root) {
14         // Start typing your C/C++ solution below
15         // DO NOT write int main() function
16         key = true;
17         if(root == NULL)
18             return key;
19         cmp(root->left,root->right);
20         return key;
21     }
22     void cmp(TreeNode *node1,TreeNode *node2)
23     {
24         if(node1 == NULL && node2 == NULL)
25             return;
26         if(node1 == NULL || node2 == NULL)
27         {
28             key = false;
29             return;
30         }
31         if(node1->val != node2->val)
32         {
33             key = false;
34             return;
35         }
36         cmp(node1->left,node2->right);
37         if(key == false)
38             return;
39         cmp(node1->right,node2->left);
40     }
41 };
42 
43 /**
44  * Definition for binary tree
45  * struct TreeNode {
46  *     int val;
47  *     TreeNode *left;
48  *     TreeNode *right;
49  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
50  * };
51  */
52 class Solution {
53 public:
54     bool isSymmetric(TreeNode *root) {
55         // Start typing your C/C++ solution below
56         // DO NOT write int main() function
57         queue<TreeNode*> q1;
58         queue<TreeNode*> q2;
59         if(root == NULL)
60             return true;
61         q1.push(root->left);
62         q2.push(root->right);
63         while(!q1.empty())
64         {
65             TreeNode * tmp1 = q1.front();
66             TreeNode * tmp2 = q2.front();
67             q1.pop();
68             q2.pop();
69             if(tmp1 == NULL && tmp2 == NULL)
70                 continue;
71             if(tmp1 == NULL || tmp2 == NULL)
72                 return false;
73             if(tmp1->val != tmp2->val)
74                 return false;
75             q1.push(tmp1->left);
76             q1.push(tmp1->right);
77             q2.push(tmp2->right);
78             q2.push(tmp2->left);
79         }
80     }
81 
82 };

 

posted on 2013-03-01 13:32  CoderJesse  阅读(129)  评论(0)    收藏  举报