判断对称二叉树-Java
题目(力扣101题)
给定一个二叉树,检查它是否是镜像对称的。
解题思路
1,首先需要判断根节点为空,接着判断左子树和右子树是否镜像对称
2,镜像对称比较左右子树时,比较left.left和right.right,以及left.right和right.left,以及左右子树是否为空
代码实现
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
// root.left和root.right是否互为镜像
return Mirror(root.left,root.right);
}
//是否镜像对称
public boolean Mirror(TreeNode left,TreeNode right) {
if(left== null && right== null){
return true;
}
if(left == null || right == null){
return false;
}
if(left.val != right.val){
return false;
}
return Mirror(left.left,right.right) && Mirror(left.right,right.left);
}