@@ -6,47 +6,33 @@ class Node {
6
6
7
7
public Node() {}
8
8
9
- public Node(int _val,List<Node> _children) {
9
+ public Node(int _val) {
10
+ val = _val;
11
+ }
12
+
13
+ public Node(int _val, List<Node> _children) {
10
14
val = _val;
11
15
children = _children;
12
16
}
13
17
};
14
18
*/
15
- class Solution {
16
- List <Integer > values = new ArrayList <>();
17
- public List <Integer > preorder (Node root ) {
18
- updateListIterative (root );
19
- return values ;
20
- }
21
-
22
- private void updateListIterative (Node root ) {
23
- if (root == null ) {
24
- return ;
25
- }
26
-
27
- Stack <Node > stack = new Stack <>();
28
- stack .push (root );
29
19
30
- while (!stack .empty ()) {
31
- Node temp = stack .pop ();
32
- values .add (temp .val );
33
-
34
- List <Node > childrens = temp .children ;
35
-
36
- for (int i =childrens .size ()-1 ; i >=0 ; i --) {
37
- stack .push (childrens .get (i ));
38
- }
39
- }
20
+ class Solution {
21
+ public List <Integer > preorder (Node root ) {
22
+ if (root == null ) {
23
+ return new ArrayList <>();
40
24
}
41
-
42
- private void updateListRecursive ( Node root ) {
43
- if (root == null ) {
44
- return ;
45
- }
46
-
47
- values . add ( root . val ) ;
48
- for (Node node : root . children ) {
49
- updateListRecursive ( node );
50
- }
25
+ List < Integer > list = new ArrayList <>();
26
+ Stack < Node > stack = new Stack <>();
27
+ stack . push (root );
28
+ while (! stack . isEmpty ()) {
29
+ Node popped = stack . pop ();
30
+ list . add ( popped . val );
31
+ List < Node > children = popped . children ;
32
+ for (int i = children . size () - 1 ; i >= 0 ; i -- ) {
33
+ stack . push ( children . get ( i ) );
34
+ }
51
35
}
36
+ return list ;
37
+ }
52
38
}
0 commit comments