Skip to content

Commit f4a9932

Browse files
committed
n-ary-tree-level-order-traversal (N 叉树的层序遍历)
1 parent 16e7707 commit f4a9932

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
|350|[两个数组的交集 II](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/)|[JavaScript](./algorithms/intersection-of-two-arrays-ii.js)|Easy|
6969
|387|[字符串中的第一个唯一字符](https://leetcode-cn.com/problems/first-unique-character-in-a-string/)|[JavaScript](./algorithms/first-unique-character-in-a-string.js)|Easy|
7070
|404|[左叶子之和](https://leetcode.cn/problems/sum-of-left-leaves/)|[JavaScript](./algorithms/sum-of-left-leaves.js)|Easy|
71+
|429|[N 叉树的层序遍历](https://leetcode.cn/problems/n-ary-tree-level-order-traversal/)|[JavaScript](./algorithms/n-ary-tree-level-order-traversal.js)|Medium|
7172
|437|[路径总和 III](https://leetcode.cn/problems/path-sum-iii/)|[JavaScript](./algorithms/path-sum-iii.js)|Medium|
7273
|509|[斐波那契数](https://leetcode.cn/problems/fibonacci-number/)|[JavaScript](./algorithms/fibonacci-number.js)|Easy|
7374
|543|[二叉树的直径](https://leetcode.cn/problems/diameter-of-binary-tree/)|[JavaScript](./algorithms/diameter-of-binary-tree.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val,children) {
4+
* this.val = val;
5+
* this.children = children;
6+
* };
7+
*/
8+
9+
/**
10+
* N 叉树的层序遍历
11+
* @param {Node|null} root
12+
* @return {number[][]}
13+
*/
14+
var levelOrder = function (root) {
15+
// 1. DFS
16+
const result = [];
17+
const dfs = (node, level = 0) => {
18+
if (node) {
19+
if (!result[level]) result[level] = [];
20+
result[level].push(node.val);
21+
const children = node.children;
22+
children.forEach((child) => {
23+
dfs(child, level + 1);
24+
});
25+
}
26+
};
27+
dfs(root);
28+
29+
return result;
30+
31+
// BFS
32+
// return bfs(root);
33+
};
34+
35+
function bfs(root) {
36+
const result = [];
37+
const queue = [];
38+
queue.push(root);
39+
40+
if (!root) {
41+
return [];
42+
}
43+
44+
while (queue.length > 0) {
45+
const temp = [];
46+
let size = queue.length;
47+
48+
while (size--) {
49+
const node = queue.shift();
50+
temp.push(node.val);
51+
const children = node.children;
52+
children.forEach((child) => queue.push(child));
53+
}
54+
result.push(temp);
55+
}
56+
57+
return result;
58+
}

0 commit comments

Comments
 (0)