LeetCode 111. 二叉树的最小深度
题目描述
思路分析
层序遍历
参考代码
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
}
if root.Left == nil && root.Right == nil {
return 1
}
leftDepth := minDepth(root.Left)
rightDepth := minDepth(root.Right)
if root.Left == nil || root.Right == nil {
// 如果左子树或右子树为空,只考虑非空子树的深度
return leftDepth + rightDepth + 1
}
return min(leftDepth, rightDepth) + 1
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
1
write your code here
相似题目
题目 | 难度 | 题解 |
---|---|---|
二叉树的层序遍历 | Medium | |
二叉树的最大深度 | Easy |
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用