101. Symmetric Tree

Posted 烁宝宝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
代码如下:
 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的主要内容,如果未能解决你的问题,请参考以下文章

101. Symmetric Tree

[LeetCode]题解(python):101-Symmetric Tree

101. Symmetric Tree

101. Symmetric Tree

LeetCode OJ 101Symmetric Tree

101. Symmetric Tree