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

101. Symmetric Tree

时间:2016-05-24 20:36:15      阅读:137      评论: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  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public boolean isSymmetric(TreeNode root) {
12         if(root==null)
13         return true;
14         TreeNode left=root.left;
15         TreeNode right=root.right;
16         
17         if(LeftTraverse(left).equals(RightTraverse(right)))
18         return true;
19         
20         return false;
21     }
22     public List<String> LeftTraverse(TreeNode root){
23         List<String> list=new ArrayList<>();
24         if(root==null)
25         return list;
26         
27         list.add(String.valueOf(root.val));
28         if(root.left!=null)
29         list.addAll(LeftTraverse(root.left));
30         else
31         list.add(" ");
32         
33         if(root.right!=null)
34         list.addAll(LeftTraverse(root.right));
35         else
36         list.add(" ");
37         return list;
38     }
39      public List<String> RightTraverse(TreeNode root){
40         List<String> list=new ArrayList<>();
41         if(root==null)
42         return list;
43         
44         list.add(String.valueOf(root.val));
45         if(root.right!=null)
46         list.addAll(RightTraverse(root.right));
47         else
48         list.add(" ");
49         
50         if(root.left!=null)
51         list.addAll(RightTraverse(root.left));
52         else
53         list.add(" ");
54         
55          
56         return list;
57     }
58 }

 

101. Symmetric Tree

标签:

原文地址:http://www.cnblogs.com/ghuosaao/p/5524612.html

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