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
代码如下:
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
TreeNode left=root.left;
TreeNode right=root.right; if(LeftTraverse(left).equals(RightTraverse(right)))
return true; return false;
}
public List<String> LeftTraverse(TreeNode root){
List<String> list=new ArrayList<>();
if(root==null)
return list; list.add(String.valueOf(root.val));
if(root.left!=null)
list.addAll(LeftTraverse(root.left));
else
list.add(" "); if(root.right!=null)
list.addAll(LeftTraverse(root.right));
else
list.add(" ");
return list;
}
public List<String> RightTraverse(TreeNode root){
List<String> list=new ArrayList<>();
if(root==null)
return list; list.add(String.valueOf(root.val));
if(root.right!=null)
list.addAll(RightTraverse(root.right));
else
list.add(" "); if(root.left!=null)
list.addAll(RightTraverse(root.left));
else
list.add(" "); return list;
}
}
上一篇:Python语法速查: 1. 数据类型与内置函数


下一篇:Java初学(八)