-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path589.java
More file actions
64 lines (55 loc) · 1.53 KB
/
589.java
File metadata and controls
64 lines (55 loc) · 1.53 KB
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
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 589. N-ary Tree Preorder Traversal
*
* Given the root of an n-ary tree, return the preorder traversal of its nodes' values.
*
* Nary-Tree input serialization is represented in their level order traversal.
* Each group of children is separated by the null value (See examples)
*/
class IterativeSolution {
public List<Integer> preorder(Node root) {
Stack<Node> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
stack.push(root);
while (!stack.empty()) {
Node n = stack.pop();
if (n == null) break;
result.add(n.val);
for (int i = n.children.size() - 1; i >= 0; i--) {
stack.push(n.children.get(i));
}
}
return result;
}
}
class RecursiveSolution {
public List<Integer> preorder(Node root) {
List<Integer> result = new ArrayList<>();
traverse(root, result);
return result;
}
private void traverse(Node node, List<Integer> result) {
if (node != null) {
result.add(node.val);
for (Node n : node.children) {
traverse(n, result);
}
}
}
}
// Definition for a Node.
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;
}
};