File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments