最小深度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
minDepth := math.MaxInt64
var dfs func(node *TreeNode, depth int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
depth ++
if node.Left == nil && node.Right == nil {
if depth < minDepth {
minDepth = depth
}
}
dfs(node.Left, depth)
dfs(node.Right, depth)
}
dfs(root, 0)
return minDepth
}

最大深度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
minDepth := 0
var dfs func(node *TreeNode, depth int)
dfs = func(node *TreeNode, depth int) {
if node == nil {
return
}
depth ++
if node.Left == nil && node.Right == nil {
if depth > minDepth {
minDepth = depth
}
}
dfs(node.Left, depth)
dfs(node.Right, depth)
}
dfs(root, 0)
return minDepth
}