剑指OfferJZ58:对称的二叉树-java版
JZ58:请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
- JZ58:请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
该题判断二叉树是否对称,即判断这颗二叉树的左右两个子树是否为镜像二叉树 详情见:镜像二叉树
public class jz58 {
boolean isSymmetrical(TreeNode pRoot) {
if(pRoot==null){
return true;
}
return solve(pRoot.left,pRoot.right);
}
private boolean solve(TreeNode node1, TreeNode node2) {
if(node1==null && node2==null){//说明左右子树同时都走到头了
return true;
}
if(node1==null || node2==null){//说明左子树走到头右子树没走到头 或者左子树没走到头右子树走到头了,这种情况都表明左右子树不对称
return false;
}
if(node1.val!=node2.val){
return false;
}
return solve(node1.left,node2.right) && solve(node1.right,node2.left);
}
}