二叉树的核心思想应用实例:二叉树镜像/二叉树的深度/平衡二叉树

关于 Tree 的最经典的递归套路

用主函数传参 root.left 和 root.right ,并用一个引用保存
同时也应该关注返回值以及返回结果

剑指 Offer 27. 二叉树的镜像

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

class Solution {
    
    
    public TreeNode mirrorTree(TreeNode root) {
    
    
        // 首先进行判空操作
        if(root == null){
    
    
            return null;
        }
        TreeNode l = mirrorTree(root.left);
        TreeNode r = mirrorTree(root.right);

        // 左右互换
        root.left = r;
        root.right = l;

        return root;
    }
}

剑指 Offer 55 - I. 二叉树的深度

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        if(l>r){
    
    
            return l+1;
        }else {
    
    
            return r+1;
        }
    }
}

剑指 Offer 55 - II. 平衡二叉树

平衡二叉树:任意节点的左右子树的高度差不超过1

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        if(l>r){
    
    
            return l+1;
        }else {
    
    
            return r+1;
        }
    }
    public boolean isBalanced(TreeNode root) {
    
    
        if(root==null){
    
    return true;}
        int l = maxDepth(root.left);
        int r = maxDepth(root.right);
        
        return Math.abs(l-r)<=1 && isBalanced(root.left) && isBalanced(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39537400/article/details/124024269