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
Note:
Bonus points if you could solve it both recursively and iteratively.
解法一:性能不怎么好的递归,先按原树创建一个镜像再比较两棵树是否一致
若要加强的话,可以直接在原树上比较,递归比较左右节点的值是否相同
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode mirror(TreeNode root){
if(root == null) return null;
TreeNode left = mirror(root.left);
TreeNode right = mirror(root.right);
TreeNode nr = new TreeNode(root.val);
nr.left = right;
nr.right = left;
return nr;
}
public boolean isSame(TreeNode p1, TreeNode p2){
if(p1==null && p2==null) return true;
if(p1 == null && p2 != null) return false;
if(p1 != null && p2 == null) return false;
return (p1.val == p2.val) && isSame(p1.left, p2.left) && isSame(p1.right, p2.right);
}
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
TreeNode p = mirror(root);
return isSame(root, p);
}
}
解法二:递归,直接比较原树的左右节点值
public class Solution {
public boolean isSame(TreeNode p1, TreeNode p2){
if(p1==null && p2==null) return true;
if(p1 == null && p2 != null) return false;
if(p1 != null && p2 == null) return false;
return (p1.val == p2.val) && isSame(p1.left, p2.right) && isSame(p1.right, p2.left);
}
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isSame(root, root);
}
}
解法三:使用两个队列分别遍历树的左右节点,并比较值
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Queue<TreeNode> q1 = new LinkedList<TreeNode>();
Queue<TreeNode> q2 = new LinkedList<TreeNode>();
if(root.left != null) q1.add(root.left);
if(root.right != null) q2.add(root.right);
while(!q1.isEmpty() && !q2.isEmpty()){
TreeNode t1 = q1.remove();
TreeNode t2 = q2.remove();
if(t1.val == t2.val){
if(t1.left != null && t2.right != null){
q1.add(t1.left);
q2.add(t2.right);
}//注意判断的条件,只有一个不为空,一个为空才不对称
else if((t1.left!=null && t2.right==null) || (t1.left==null && t2.right!=null))
return false;
if(t1.right != null && t2.left != null){
q1.add(t1.right);
q2.add(t2.left);
}
else if((t1.right !=null && t2.left==null) || (t1.right==null && t2.left!=null))
return false;
}
else{
return false;
}
}
if(q1.isEmpty() && q2.isEmpty())
return true;
return false;
}
}