LeetCode 559. N 叉树的最大深度

题目描述

559. N 叉树的最大深度

image-20230312171608549

image-20230312171605492

思路分析

层序遍历

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func maxDepth(root *Node) int {
	if root == nil {
		return 0
	}

	res := 0

	for _, child := range root.Children {
		depth := maxDepth(child)
		if depth > res {
			res = depth
		}
	}

	return res + 1
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func maxDepth(root *Node) int {
	if root == nil {
		return 0
	}

	var queue []*Node
	queue = append(queue, root)
	depth := 0

	for len(queue) > 0 {
		size := len(queue)
		for i := 0; i < size; i++ {
			cur := queue[0]
			queue = queue[1:]
			for _, child := range cur.Children {
				queue = append(queue, child)
			}
		}
		depth++
	}

	return depth
}

➡️ 点击查看 Java 题解

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