-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path589.n-叉树的前序遍历.js
85 lines (81 loc) · 1.53 KB
/
589.n-叉树的前序遍历.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* @lc app=leetcode.cn id=589 lang=javascript
*
* [589] N 叉树的前序遍历
*
* https://leetcode.cn/problems/n-ary-tree-preorder-traversal/description/
*
* algorithms
* Easy (76.14%)
* Likes: 278
* Dislikes: 0
* Total Accepted: 148.2K
* Total Submissions: 194.6K
* Testcase Example: '[1,null,3,2,4,null,5,6]'
*
* 给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。
*
* n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。
*
*
* 示例 1:
*
*
*
*
* 输入:root = [1,null,3,2,4,null,5,6]
* 输出:[1,3,5,6,2,4]
*
*
* 示例 2:
*
*
*
*
* 输入: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]
* 输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]
*
*
*
*
* 提示:
*
*
* 节点总数在范围 [0, 10^4]内
* 0 <= Node.val <= 10^4
* n 叉树的高度小于或等于 1000
*
*
*
*
* 进阶:递归法很简单,你可以使用迭代法完成此题吗?
*
*/
// @lc code=start
/**
* // Definition for a Node.
* function Node(val, children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number[]}
*/
const fn = (root, ans = []) => {
if (root === null) return [];
ans.push(root.val);
if (root.children) {
for (const child of root.children) {
fn(child, ans);
}
}
};
var preorder = function (root, ans = []) {
// let ans = []
fn(root, ans);
return ans;
};
// @lc code=end