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
[code]
递归版本
public class Solution {
public boolean isSymmetric(TreeNode root) {
ArrayList<TreeNode> level=new ArrayList<TreeNode>();
if(root==null)return true;
else level.add(root);
return helper(level);
}
boolean helper(ArrayList<TreeNode> level)
{
if(level.size()==0)return true;
int i=0, j=level.size()-1;
while(i<=j)
{
TreeNode l1=level.get(i).left, r1=level.get(i).right;
TreeNode l2=level.get(j).left, r2=level.get(j).right;
if( (l1==null && r2!=null) || (l1!=null && r2==null) )return false;
if( l1!=null && r2!=null && l1.val!=r2.val )return false;
if( (l2==null && r1!=null) || (l2!=null && r1==null) )return false;
if( l2!=null && r1!=null && l2.val!=r1.val )return false;
i++;j--;
}
int n=level.size();
for(i=0;i<n;i++)
{
TreeNode node=level.remove(0);
if(node.left!=null)level.add(node.left);
if(node.right!=null)level.add(node.right);
}
return helper(level);
}
}