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
页面信息
location:
protocol
: host
: hostname
: origin
: pathname
: href
: document:
referrer
: navigator:
platform
: userAgent
: