思路:
复制出一个二叉树b,加上原二叉树为a。
a.val==b.val
a.left.val==b.right.val
a.right.val=b.left.val
class Solution {
//递归方式
public boolean isSymmetric02(TreeNode root) {
if (root==null){
return false;
}
return isSymmetric02(root.left,root.right);
}
private boolean isSymmetric02(TreeNode left, TreeNode right) {
if (left==null||right==null){
return left == null && right == null;
}
return left.val==right.val&&isSymmetric02(left.left,right.right)
&&isSymmetric02(right.left,left.right);
}
public boolean isSymmetric(TreeNode root) {
if (root==null){
return false;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
queue.add(root);
while (!queue.isEmpty()){
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if (left==null||right==null){
if (left==null&&right==null){
continue;
}else {
return false;
}
}
if (left.val!=right.val){
return false;
}
queue.add(left.left);
queue.add(right.right);
queue.add(left.right);
queue.add(right.left);
}
return true;
}
}
还有一种方法,先反转然后跟原来树对比是否相等