首页 > 其他 > 详细

Symmetric Tree

时间:2015-07-15 10:39:45      阅读:209      评论: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

 

Note:
Bonus points if you could solve it both recursively and iteratively.

思路:这个没啥可说的。两种解法递归和迭代。

 1 public boolean isSymmetric(TreeNode root) {
 2         if (root == null) return true;
 3         return helper(root.left, root.right);
 4     }
 5     private boolean helper(TreeNode left, TreeNode right) {
 6         if (left == null) return right == null;
 7         if (right == null) return left == null;
 8         if (left.val == right.val) {
 9             return helper(left.left, right.right) && helper(left.right, right.left);
10         }else{
11             return false;
12         }
13     }
 1 public boolean isSymmetric(TreeNode root) {
 2         if (root == null) {
 3             return true;
 4         }
 5         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 6         queue.offer(root.left);
 7         queue.offer(root.right);
 8         TreeNode left;
 9         TreeNode right;
10         while (!queue.isEmpty()) {
11             left = queue.poll();
12             right = queue.poll();
13             if (left == null && right == null) {
14                 continue;
15             }
16             if (left == null || right == null || left.val != right.val) {
17                 return false;
18             }
19             queue.offer(left.left);
20             queue.offer(right.right);
21             queue.offer(left.right);
22             queue.offer(right.left);
23         }
24         return true;
25     }

 

Symmetric Tree

原文:http://www.cnblogs.com/gonuts/p/4647423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!