LeetCode 559. N 叉树的最大深度
题目描述
思路分析
层序遍历
参考代码
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
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用