111. 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.
้ข็ฎๅคงๆ #
็ปๅฎไธไธชไบๅๆ ๏ผๆพๅบๅ ถๆๅฐๆทฑๅบฆใๆๅฐๆทฑๅบฆๆฏไปๆ น่็นๅฐๆ่ฟๅถๅญ่็น็ๆ็ญ่ทฏๅพไธ็่็นๆฐ้ใ่ฏดๆ: ๅถๅญ่็นๆฏๆๆฒกๆๅญ่็น็่็นใ
่งฃ้ขๆ่ทฏ #
- ้ๅฝๆฑๅบๆ น่็นๅฐๅถๅญ่็น็ๆทฑๅบฆ๏ผ่พๅบๆๅฐๅผๅณๅฏ
ไปฃ็ #
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil {
return minDepth(root.Right) + 1
}
if root.Right == nil {
return minDepth(root.Left) + 1
}
return min(minDepth(root.Left), minDepth(root.Right)) + 1
}