代码1——dfs:
- dfs递归
- 退出条件root == nil, 或其左右节点皆为nil
- 如果左节点不为nil, 则返回左节点的深度,右节点不为nil,则返回右节点的深度
- 如果都不为nil,则返回较小的深度
- 最后返回md + 1
- 因为md是子节点的深度,故而加1
与求最大深度不同在于,最大深度只需要考虑当前节点为nil即可,
/**
* 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 && root.Right == nil {
return 1
}
md := math.MaxInt32
if root.Left != nil {
md = min(minDepth(root.Left), md)
}
if root.Right != nil {
md = min(minDepth(root.Right), md)
}
return md + 1
}
func min(a,b int) int {
if a < b {
return a
}
return b
}
bfs:
- queue模拟队列,记录层序遍历
- count记录当前节点位于哪一层,也就是当前节点的深度
- for遍历,直到碰到当前节点的字节点均为nil,则返回当前节点的深度
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
queue := []*TreeNode{}
count := []int{}
queue = append(queue, root)
count = append(count, 1)
for i := 0; i < len(queue); i++ {
node := queue[i]
depth := count[i]
if node.Left == nil && node.Right == nil {
return depth
}
if node.Left != nil {
queue = append(queue, node.Left)
count = append(count, depth + 1)
}
if node.Right != nil {
queue = append(queue, node.Right)
count = append(count, depth + 1)
}
}
return 0
}