Skip to content

Commit 1a6ef7e

Browse files
authored
Create 589. N-ary Tree Preorder Traversal
1 parent 6939f83 commit 1a6ef7e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

589. N-ary Tree Preorder Traversal

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
List<Integer> result = new ArrayList<>();
3+
public List<Integer> preorder(Node root) {
4+
if(root == null) return result;
5+
preorderHelper(root);
6+
return result;
7+
}
8+
9+
public void preorderHelper(Node node) {
10+
if(node.children == null) return;
11+
result.add(node.val);
12+
for(Node child : node.children) {
13+
preorderHelper(child);
14+
}
15+
}
16+
}
17+
18+
class Solution {
19+
List<Integer> result = new ArrayList<>();
20+
public List<Integer> preorder(Node root) {
21+
if(root == null) return result;
22+
23+
Stack<Node> stack = new Stack<>();
24+
stack.push(root);
25+
26+
while(!stack.isEmpty()) {
27+
Node curr = stack.pop();
28+
result.add(curr.val);
29+
//Pushing in children in reverse order
30+
for(int i = curr.children.size()-1; i >= 0; i--) {
31+
stack.push(curr.children.get(i));
32+
}
33+
}
34+
35+
return result;
36+
}
37+
38+
}}

0 commit comments

Comments
 (0)