码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Symmetric Tree Tree(对称的树)

时间:2015-10-23 16:10:00      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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

判断一颗树是否对称,首先用递归的方法当然比较容易解决:

 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         if(!root->left && !root->right)
16             return true;
17         if(root->left && !root->right || !root->left && root->right)
18             return false;
19         return checkSymmetric(root->left, root->right);
20     }
21 
22     bool checkSymmetric(TreeNode * left, TreeNode * right)
23     {
24         if(!left && !right)
25             return true;
26         if(!left && right || left && !right)
27             return false;
28         if(left->val != right->val)
29             return false;
30         return checkSymmetric(left->left, right->right) && checkSymmetric(left->right, right->left);
31     }
32 };

 

题目还要求用非递归的方式来实现,制造两个队列就可以实现了:

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

 

LeetCode OJ:Symmetric Tree Tree(对称的树)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4904657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!