Leetcode 101. Symmetric Tree

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

分析:这道题既可以用深度优先搜索DFS,也可以用广度优先搜索BFS。

思路:(1)深度优先搜索的思路为:
(1)传入root的左子树和右子树。如果两个都为NULL,则是对称的。

(2)如果两边都不为NULL并且两边的所对应的val相等,那就判断root->left->left和root->right->right是否对称,且判断root->left->right和root->right->left是否对称。。。
其余情况下return false;

 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 func(TreeNode* left, TreeNode* right){
13         if(left == NULL && right == NULL)
14             return true;
15         if(left != NULL && right != NULL && left->val == right->val)
16             return (func(left->right, right->left) && func(right->right, left->left));
17         else
18             return false;
19     }
20     bool isSymmetric(TreeNode* root) {
21         if(root == NULL)
22             return true;
23         else
24             return func(root->left, root->right);
25     }
26 };


(2)用广度优先搜索来做:
建立两个队列,lq和rq,每次比较队首的两个元素是否相等。
lq队列的队首l出列后,将它的left和right分别入队;
rq队列的队首r出列后,将它的right和left分别入队。
因为判断是否对称是这样比较的:
l->left 与 r->right
l->right 与 r->left比较。
 

 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 isSymmetric(TreeNode* root) {
13         if(root == NULL)
14             return true;
15         queue<TreeNode*> lq, rq;
16         TreeNode *l, *r;
17         lq.push(root->left);
18         rq.push(root->right);
19         while(!lq.empty() && !rq.empty()){
20             l = lq.front();
21             r = rq.front();
22             lq.pop();
23             rq.pop();
24             if(l == NULL && r == NULL)
25                 continue;
26             if(l == NULL || r == NULL || l->val != r->val)
27                 return false;
28             lq.push(l->left);
29             lq.push(l->right);
30             rq.push(r->right);
31             rq.push(r->left);
32         }
33         if(lq.empty() && rq.empty())
34             return true;
35         else
36             return false;
37     
38     }
39 };

 

posted @ 2016-05-17 22:08  琴影  阅读(176)  评论(0编辑  收藏  举报