返回介绍

Minimum Depth of Binary Tree

发布于 2025-02-22 13:01:31 字数 1806 浏览 0 评论 0 收藏 0

Source

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.

Example
Given a binary tree as follow:

    1

   /   \

   2     3

      /  \

    4    5
The minimum depth is 2

题解

注意审题,题中的最小深度指的是从根节点到 最近的叶子节点(因为题中的最小深度是 the number of nodes,故该叶子节点不能是空节点) ,所以需要单独处理叶子节点为空的情况。此题使用 DFS 递归实现比较简单。

Java

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *   public int val;
 *   public TreeNode left, right;
 *   public TreeNode(int val) {
 *     this.val = val;
 *     this.left = this.right = null;
 *   }
 * }
 */
public class Solution {
  /**
   * @param root: The root of binary tree.
   * @return: An integer.
   */
  public int minDepth(TreeNode root) {
    if (root == null) return 0;

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

    // current node is not leaf node
    if (root.left == null) {
      return 1 + rightDepth;
    } else if (root.right == null) {
      return 1 + leftDepth;
    }

    return 1 + Math.min(leftDepth, rightDepth);
  }
}

源码分析

建立好递归模型即可,左右子节点为空时需要单独处理下。

复杂度分析

每个节点遍历一次,时间复杂度 O(n)O(n)O(n). 不计栈空间的话空间复杂度 O(1)O(1)O(1).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文