Skip to content

Commit 2ae66f9

Browse files
committed
589. N 叉树的前序遍历
1 parent 197cc05 commit 2ae66f9

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@
126126
|551|[学生出勤记录 I](https://leetcode.cn/problems/student-attendance-record-i/)|[JavaScript](./algorithms/student-attendance-record-i.js)|Easy|
127127
|557|[反转字符串中的单词 III](https://leetcode.cn/problems/reverse-words-in-a-string-iii/)|[JavaScript](./algorithms/reverse-words-in-a-string-iii.js)|Easy|
128128
|566|[重塑矩阵](https://leetcode.cn/problems/reshape-the-matrix/)|[JavaScript](./algorithms/reshape-the-matrix.js)|Easy|
129+
|589|[N 叉树的前序遍历](https://leetcode.cn/problems/n-ary-tree-preorder-traversal/)|[JavaScript](./algorithms/n-ary-tree-preorder-traversal.js)|Easy|
129130
|598|[范围求和 II](https://leetcode.cn/problems/range-addition-ii/)|[JavaScript](./algorithms/range-addition-ii.js)|Easy|
130131
|617|[合并二叉树](https://leetcode.cn/problems/merge-two-binary-trees/)|[JavaScript](./algorithms/merge-two-binary-trees.js)|Easy|
131132
|628|[三个数的最大乘积](https://leetcode.cn/problems/maximum-product-of-three-numbers/)|[JavaScript](./algorithms/maximum-product-of-three-numbers.js)|Easy|
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val, children) {
4+
* this.val = val;
5+
* this.children = children;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {Node|null} root
11+
* @return {number[]}
12+
*/
13+
var preorder = function (root) {
14+
// DFS
15+
const result = [];
16+
const dfs = (node) => {
17+
if (node) {
18+
result.push(node.val);
19+
const children = node.children;
20+
children.forEach((child) => {
21+
dfs(child);
22+
});
23+
}
24+
};
25+
26+
dfs(root);
27+
28+
return result;
29+
};

0 commit comments

Comments
 (0)