leetcode-111 二叉树的最小深度

姊妹篇:

leetcode-104 二叉树的最大深度




111. 二叉树的最小深度

难度: 简单




  • 递归求出根节点到叶子节点的深度,输出最小值即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

/**
* 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
}



//之所以定义left和right,为了防止下面return时还有再次计算
left := minDepth(root.Left)
right := minDepth(root.Right)
if left > right {
return right + 1
} else {
return left + 1
}





三道题套路解决递归问题

如链接失效,可点击

文章目录