0111. Minimum Depth of Binary Tree

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
}


โฌ…๏ธไธŠไธ€้กต

ไธ‹ไธ€้กตโžก๏ธ

Calendar Apr 8, 2023
Edit Edit this page
ๆœฌ็ซ™ๆ€ป่ฎฟ้—ฎ้‡:  ๆฌก ๆ‚จๆ˜ฏๆœฌ็ซ™็ฌฌ  ไฝ่ฎฟ้—ฎ่€