【Minimum Depth of Binary Tree】

这篇博客介绍了如何在Java中找到二叉树的最小深度。提供了两种方法,一种是递归实现,另一种是非递归实现。递归方案通过比较左右子树的最小深度来确定;非递归方案使用广度优先搜索策略,逐层遍历直到找到第一个叶子节点。这两种方法都在O(n)的时间复杂度内完成,其中n是树的节点数。
摘要由CSDN通过智能技术生成

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.
Example 1:

在这里插入图片描述

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

Java Completion:

/**
 * 递归实现
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int depth = 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        if (left != 0 && right != 0) depth = Math.min(left, right);
        if (left == 0 || right == 0) depth = Math.max(left, right);
        return depth + 1;
    }
}
/**
 * 非递归实现
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> stack = new LinkedList<>();
        stack.offer(root);
        int depth = 0;
        TreeNode rightMost = root;
        while (!stack.isEmpty()) {
            TreeNode poll = stack.poll();
            if (poll.left == null && poll.right == null) break;
            if (poll.left != null) stack.offer(poll.left);
            if (poll.right != null) stack.offer(poll.right);
            if (poll == rightMost) {
                depth++;
                rightMost = poll.right == null ? poll.left : poll.right;
            }
        }
        return depth;
    }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值