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

关于 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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值