LeetCode 111. 二叉树的最小深度

题目:

​​​​​​力扣

题解一:层序遍历

通过层序遍历每一层的节点,当遍历到叶子节点,该叶子节点的深度即为二叉树的最小深度,时间复杂度:O(n)

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 1;
        while (!queue.isEmpty()) {
            // 遍历当前层的节点
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                // 如果当前节点左右子树都为空,说明当前为叶子节点,直接返回叶子节点的深度
                if (node.left == null && node.right == null) {
                    return depth;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            depth++;
        }

        return 0;
    }

题解二:递归遍历

递归遍历左右子树,取左右子树最小的的深度+1。

递归边界:

1.当root左右孩子都为null时,返回1

2.当root左右孩子有一个为null时,返回不为null的孩子节点深度

3.当root左右孩子都不为null,返回左右孩子较小深度

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        // 当左右孩子有null时,必定其深度为0,所以这里需要取左右孩子较大的深度
        if (root.left == null || root.right == null) {
            return Math.max(leftDepth, rightDepth) + 1;
        }

        // 左右孩子都不为null,取最小深度
        return Math.min(leftDepth, rightDepth) + 1;
    }

当左右孩子为null时,其深度为0,所以代码可以简写直接返回 leftDepth + rightDepth + 1

    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        return root.left == null || root.right == null ? leftDepth + rightDepth + 1 : Math.min(leftDepth, rightDepth) + 1;
    }

时间复杂度:O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值