0559. N 叉树的最大深度【简单】
1. 📝 题目描述
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 1:

txt
输入:root = [1,null,3,2,4,null,5,6]
输出:31
2
2
示例 2:

txt
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:51
2
2
提示:
- 树的深度不会超过
1000。 - 树的节点数目位于
[0, 10^4]之间。
2. 🎯 s.1 - DFS 深度优先搜索
js
/**
* // Definition for a _Node.
* function _Node(val,children) {
* this.val = val === undefined ? null : val;
* this.children = children === undefined ? null : children;
* };
*/
/**
* @param {_Node|null} root
* @return {number}
*/
var maxDepth = function (root) {
// 空节点深度为 0
if (!root) {
return 0
}
// 叶子节点深度为 1
if (!root.children || root.children.length === 0) {
return 1
}
// 计算所有子树的最大深度
let maxChildDepth = 0
for (let child of root.children) {
maxChildDepth = Math.max(maxChildDepth, maxDepth(child))
}
// 当前节点深度 = 子树最大深度 + 1
return maxChildDepth + 1
}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
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
- 时间复杂度:
,其中 n 是 N 叉树的节点数,需要访问每个节点一次 - 空间复杂度:
,其中 h 是 N 叉树的高度,递归调用栈的深度。最坏情况下为 (树退化为链表)
3. 🎯 s.2 - BFS 广度优先搜索
js
/**
* // Definition for a _Node.
* function _Node(val,children) {
* this.val = val === undefined ? null : val;
* this.children = children === undefined ? null : children;
* };
*/
/**
* @param {_Node|null} root
* @return {number}
*/
var maxDepth = function (root) {
if (!root) return 0
const queue = [root]
let depth = 0
while (queue.length > 0) {
depth++
const levelSize = queue.length
// 处理当前层的所有节点
for (let i = 0; i < levelSize; i++) {
const node = queue.shift()
if (node.children) {
queue.push(...node.children)
}
}
}
return depth
}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
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
- 时间复杂度:
,需要访问每个节点一次 - 空间复杂度:
,其中 是树的最大宽度,最坏情况下为