你的位置:首页 > Java教程

[Java教程]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     else31     list.add(" ");32     33     if(root.right!=null)34     list.addAll(LeftTraverse(root.right));35     else36     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     else48     list.add(" ");49     50     if(root.left!=null)51     list.addAll(RightTraverse(root.left));52     else53     list.add(" ");54     55     56     return list;57   }58 }