当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.111.Minimum Depth of Binary Tree 二叉树的最小深度

LeetCode.111.Minimum Depth of Binary Tree 二叉树的最小深度

题目描述

111 Minimum Depth of Binary Tree
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

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:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.


解题过程

二叉树的最小深度
第一次提交在用例 [1,2] 上错了,因为没看清题目描述
叶子节点是指没有子节点的节点,所以1不是叶子节点,题目问的是根到叶子节点的最短距离,[1,2] 用例中是 1->2,举例为2

public int minDepth(TreeNode root) {
    if (null == root) {
        return 0;
    }
    if (null == root.left && null == root.right) {
       return 1;
    }
    if (null == root.left || null == root.right) {
        return null == root.left ? minDepth(root.right) + 1 : minDepth(root.left) + 1;
    }
    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}

GitHub代码

algorithms/leetcode/leetcode/_111_MinimumDepthOfBinaryTree.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_111_MinimumDepthOfBinaryTree.java


上一篇 GitLab

下一篇 LeetCode.110.Balanced Binary Tree 是否平衡二叉树

阅读
评论
232
阅读预计1分钟
创建日期 2020-01-25
修改日期 2020-01-25
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论