//判断二叉树是否镜面对称,即判断左右子树是否互为镜像
public class Solution {
public boolean isSymmetric(TreeNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == null) return true;
return isSymmetric(root.left,root.right);
}
//判断两颗树是否互为镜像,同时满足以下三个条件
//1.root值相等
//2.A的左子树和B的右子树互为镜像
//3.A的右子树和B的左子树互为镜像
public boolean isSymmetric(TreeNode root1,TreeNode root2){
if(root1 == null&&root2 == null) return true;
if(root1 == null||root2 == null) return false;
if(root1.val!=root2.val) return false;
return isSymmetric(root1.right,root2.left)&&isSymmetric(root1.left,root2.right);
}
}
题2,求一个二叉树的镜像
递归互换左右子树,注意与上题的区别
public TreeNode createSymmetric(TreeNode root){
if(root == null) return null;
TreeNode cloneRoot = new TreeNode(root.value);
cloneRoot.rchild = createSymmetric(root.lchild);
cloneRoot.lchild = createSymmetric(root.rchild);
return cloneRoot;
}