代码随想录 第16天 二叉树的最大深度和最小深度 完全二叉树的节点

二叉树的最大和最小深度

求二叉树最大和最小深度 都是使用 后序遍历 左右中 代码更加简洁
后序遍历实际上求的是高度
深度 怎么得到 只需要让高度 加1 因为根节点不是孩子
所以返回的时候 要加1
根节点的高度就是二叉树最大深度

class solution {
    /**
     * 递归法
     */
    public int maxDepth(TreeNode root) {
    if(root == 0){
    return 0;}
    int leftdepth = new maxDepth(root.left);
    int rightdepth = new maxDepth(root.right);
    return 1+Math.max(leftdepth,rightdepth);
    }

最小深度的求法
和最大深度有所区别
需要判断左右节点 为空的情况 目的是找出叶子节点到根节点最短的路径
如果左孩子或者右孩子的左节点或者右节点先为空 那么说明 这个路径最短 只需要对当前高度加1

class Solution {
    /**
     * 递归法,相比求MaxDepth要复杂点
     * 因为最小深度是从根节点到最近**叶子节点**的最短路径上的节点数量
     */
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null && root.right !=null) {
        //右节点不为空
            return rightDepth + 1;
        }
        if (root.right == null && root.left!= null) {
            return leftDepth + 1;
        }
        // 左右结点都不为null 返回最小的那个高度加1
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

完全二叉树节点

这道题
解题思路

也是使用后序遍历
不同的是
我们这里需要两个终止条件 一个是根节点为空 一个是 判断满二叉树 然后求节点 再去递归

class Solution {
    /**
     * 针对完全二叉树的解法
     *
     * 满二叉树的结点数为:2^depth - 1
     */
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
        while (left != null) {  // 求左子树深度
            left = left.left;
            leftDepth++;
        }
        while (right != null) { // 求右子树深度
            right = right.right;
            rightDepth++;
        }
        if (leftDepth == rightDepth) {
            return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
        }
        //这里其实是简写
        // 准确写是 分别new 两个对象 然后去递归 然后再返回 顺序是 左右中 中是 返回到上一个节点 把值给它 
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值