-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathN_aryTreePreorderTraversal589.java
66 lines (46 loc) · 1.1 KB
/
N_aryTreePreorderTraversal589.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package MustDoEasyList;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
}
public class N_aryTreePreorderTraversal589 {
// recursive solution
public List<Integer> answer = new ArrayList<Integer>();
public List<Integer> preorder(Node root) {
if (root == null)
return answer;
answer.add(root.val);
for (Node node : root.children) {
preorder(node);
}
return answer;
}
public List<Integer> result = new ArrayList<Integer>();
public List<Integer> preorderIterative(Node root) {
if (root == null)
return result;
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.isEmpty()) {
Node curr = stack.pop();
result.add(curr.val);
// inserting children of current node to stack in reverse order
for (int i = curr.children.size() - 1; i >= 0; i--) {
stack.push(curr.children.get(i));
}
}
return result;
}
}