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