Skip to content

Commit c84fd19

Browse files
committed
feat: Solve n-ary preorder lecture
- Leetcode, #589
1 parent 61364dc commit c84fd19

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

n-ary-tree-preorder-traversal.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Leetcode, 589
3+
* Given an n-ary tree, return the preorder traversal of its nodes' values.
4+
* Nary-Tree input serialization is represented in their level order traversal,
5+
* each group of children is separated by the null value (See examples).
6+
*
7+
* Follow up:
8+
* Recursive solution is trivial, could you do it iteratively?
9+
*/
10+
11+
12+
/**
13+
* // Definition for a Node.
14+
* function Node(val,children) {
15+
* this.val = val;
16+
* this.children = children;
17+
* };
18+
*/
19+
/**
20+
* @param {Node} root
21+
* @return {number[]}
22+
*/
23+
function preorder(root) {
24+
const preOrder = [];
25+
if (root) {
26+
const stack = [root];
27+
let node;
28+
while (stack.length > 0) {
29+
node = stack.pop();
30+
preOrder.push(node.val);
31+
stack.push(...node.children.reverse());
32+
}
33+
}
34+
return preOrder;
35+
};

0 commit comments

Comments
 (0)