题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
翻译:
给定一个二叉树,检测它是不是一个它自己的镜像(左右对称)。
代码:
/** * 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;
}else{
return isSame(root.left,root.right);
}
}
public boolean isSame(TreeNode left,TreeNode right) {
if(left==null&&right==null){
return true;
}else if(left!=null&&right!=null){
if(left.val!=right.val){
return false;
}
boolean res1=isSame(left.left,right.right);
boolean res2=isSame(left.right,right.left);
if(res1&&res2){
return true;
}else{
return false;
}
}else{
return false;
}
}
}