给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 3,9,20,null,null,15,7,
示例1
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// 注意审题,没有子节点的 node 才是 leaf
func minDepth(root *TreeNode) int {
switch {
case root == nil:
return 0
case root.Left == nil:
return 1 + minDepth(root.Right)
case root.Right == nil:
return 1 + minDepth(root.Left)
default:
return 1 + min(minDepth(root.Left), minDepth(root.Right))
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。