当前位置 : 首页 » 文章分类 :  算法  »  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],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its minimum depth = 2.


解题过程

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

  1. public int minDepth(TreeNode root) {
  2. if (null == root) {
  3. return 0;
  4. }
  5. if (null == root.left && null == root.right) {
  6. return 1;
  7. }
  8. if (null == root.left || null == root.right) {
  9. return null == root.left ? minDepth(root.right) + 1 : minDepth(root.left) + 1;
  10. }
  11. return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
  12. }

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 是否平衡二叉树

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

页面信息

location:
protocol: http:
host: masikkk.com
hostname: masikkk.com
origin: http://masikkk.com
pathname: /article/LeetCode.111.MinimumDepthOfBinaryTree/
href: http://masikkk.com/article/LeetCode.111.MinimumDepthOfBinaryTree/
document:
referrer:
navigator:
platform: Linux x86_64
userAgent: Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)

评论