LeetCode 111. 二叉树的最小深度

题目描述

111. 二叉树的最小深度

image-20230311201039813

思路分析

层序遍历

参考代码

image-20250510071133712

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
	}

	// 左右子树都不为空,返回较小深度 + 1
	left := minDepth(root.Left)
	right := minDepth(root.Right)

	return min(left, right) + 1
}

image-20250510071112755

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
func minDepth(root *TreeNode) int {
	if root == nil {
		return 0
	}

	queue := []*TreeNode{root}
	depth := 1

	for len(queue) > 0 {
		size := len(queue)
		for i := 0; i < size; i++ {
			cur := queue[0]
			queue = queue[1:]

			// 遇到叶子节点,返回当前深度
			if cur.Left == nil && cur.Right == nil {
				return depth
			}

			if cur.Left != nil {
				queue = append(queue, cur.Left)
			}
			if cur.Right != nil {
				queue = append(queue, cur.Right)
			}
		}
		depth++
	}

	return depth
}

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2024/76438130
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!