Day16 二叉树part03

本文介绍了如何使用递归方法解决二叉树的问题,包括计算最大深度(非空节点层数)、最小深度(从根到最浅叶子节点的最少步数)以及完全二叉树的节点总数。通过示例代码展示了解决方案的逻辑和实现。
摘要由CSDN通过智能技术生成

Day16 二叉树part03

104.二叉树的最大深度

我的思路:
递归,最后注意是1 + max(left, right)

解答:

class Solution {
    public int maxDepth(TreeNode root) {
        return getMaxDepth(root);
    }

    public int getMaxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = getMaxDepth(root.left);
        int right = getMaxDepth(root.right);
        int max_Depth = Math.max(left, right) + 1;
        return max_Depth;
    }
}

111.二叉树的最小深度

我的思路:
列举出左右子树为空的特殊情况后,递归返回1 + min(left, right)

解答:

class Solution {
    public int minDepth(TreeNode root) {
        return getMinDepth(root);
    }
    public int getMinDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = getMinDepth(root.left);
        int right = getMinDepth(root.right);
        if(root.left == null && root.right != null) {
            return 1 + right;
        }
        if(root.left != null && root.right == null) {
            return 1 + left;
        }
        int min_Depth = 1 + Math.min(left, right);
        return min_Depth;
    }
}

222.完全二叉树的节点个数

我的思路:
完全二叉树结点 = left + right + 1

解答:

class Solution {
    public int countNodes(TreeNode root) {
        return getNodes(root);
    }
    public int getNodes(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int left = getNodes(root.left);
        int right = getNodes(root.right);
        int all = left + right + 1;
        return all;
    }
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值