剑指offer-----对称的二叉树

1、题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

2、思路

树A的左节点等于树B的右结点,树A的右结点等于树B的左节点。刚开始根节点便是树A和树B的根节点,后来,树A是根节点的左节点,树B是根节点的右结点,依次类推。

3、代码实现

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;


    public TreeNode(int val) {
        this.val = val;


    }


}
*/
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        
        if(pRoot == null){//null树是对称二叉树
            return true;
        }
        return isSymmetrical(pRoot,pRoot);
        
    }
    boolean isSymmetrical(TreeNode root1,TreeNode root2){
        if(root1==null && root2==null){
            return true;
        }
        if(root1==null && root2!=null){
            return false;
        }
        if(root1!=null && root2==null){
            return false;
        }
        if(root1.val != root2.val){
            return false;
        }
        
        return isSymmetrical(root1.left,root2.right)&&isSymmetrical(root1.right,root2.left);
    } 
}

猜你喜欢

转载自blog.csdn.net/g1607058603/article/details/81058658