Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3But the following
[1,2,2,null,3,null,3]
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;
return check(root.left,root.right);
}
public boolean check(TreeNode q, TreeNode p)
{
if(q==null||p==null)
return p==q;
return check(q.left,p.right)&&check(q.right,p.left)&&q.val==p.val;
}
}
上述方法采用的是递归的思想; 另一种不用递归的方法下面给出
方法二 :
/**
* 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)
{
LinkedList<TreeNode> q=new LinkedList<TreeNode>();
LinkedList<TreeNode> p=new LinkedList<TreeNode>();
q.addLast(root);
p.addLast(root);
while(!q.isEmpty())
{
TreeNode t1=q.remove();
TreeNode t2=p.remove();
if(t1==null&&t2==null)
continue;
if(t1==null||t2==null)
return false;
if(t1.val!=t2.val)
return false;
q.add(t1.left);
q.add(t1.right);
p.add(t2.right);
p.add(t2.left);
}
return true;
}
}