111-Minimum Depth of Binary Tree
Description
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.
問題描述
給定一個二叉樹, 返回它的最低高度
最低高度為根節點到最近的葉節點的路徑的節點數
問題分析
與求高度類似, 需要注意節點的左右子樹為空的情況
解法
public class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
//注意這裡的兩項判斷, 必須是根節點到葉子節點
if (left == 0) return 1 + right;
if (right == 0) return 1 + left;
return 1 + Math.min(left, right);
}
}
相關文章
- 104. Maximum Depth of Binary Tree
- [leetcode]maximum-depth-of-binary-treeLeetCode
- 104-Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary TreeLeetCode
- LeetCode のminimum-depth-of-binary-treeLeetCode
- 104. Maximum Depth of Binary Tree(圖解)圖解
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- 662. Maximum Width of Binary Tree
- 173. Binary Search Tree Iterator
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 637-Average of Levels in Binary Tree
- 669-Trim a Binary Search Tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode