剑指Offer-55——对称的二叉树

题目描述

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

思路描述

首先需要知道什么是对称二叉树。以及他的镜像是什么样的。
在这里插入图片描述
其次是,明白这样多次的遍历左右子树,肯定是要用到递归的思想来解决的。递归,真就是想到了就很简单,理解起来也很简单。但没想到突破点,真的是想破脑袋也不会明白。
这里就采用的是,同时递归左右子树,来获得最终结果。

代码

/*
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) return true;
        return isSymmetrical(pRoot.right,pRoot.left);
    }
    boolean isSymmetrical(TreeNode rootRigth,TreeNode rootLeft){
    
    
        if(rootRigth==null&&rootLeft==null) return true;//左右都遍历完了说明是对称
        if(rootRigth==null||rootLeft==null) return false;//其中有一个为空了,说明不是
        if(rootRigth.val == rootLeft.val){
    
    
            //如果左右的值相等,进行递归
            return isSymmetrical(rootRigth.left,rootLeft.right)
                &&isSymmetrical(rootRigth.right,rootLeft.left);
        }else{
    
    
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/H1517043456/article/details/107517543