Skip to content

Commit a886cc4

Browse files
authored
Update N-ary Tree Preorder Traversal.java
1 parent 675c0dc commit a886cc4

File tree

1 file changed

+21
-35
lines changed

1 file changed

+21
-35
lines changed

Easy/N-ary Tree Preorder Traversal.java

Lines changed: 21 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6,47 +6,33 @@ class Node {
66
77
public Node() {}
88
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) {
1014
val = _val;
1115
children = _children;
1216
}
1317
};
1418
*/
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);
2919

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<>();
4024
}
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+
}
5135
}
36+
return list;
37+
}
5238
}

0 commit comments

Comments
 (0)