589. N-ary Tree Preorder Traversal

DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<Integer> preorder(Node root) {
// root -> child1 -> child2 -> child3

List<Integer> resultList = new ArrayList<>();
dfs(resultList, root);
return resultList;
}

private void dfs(List<Integer> resultList, Node node) {
if (node == null) {
return;
}

resultList.add(node.val);

if (node.children != null) {
for (Node child : node.children) {
dfs(resultList, child);
}
}
}
}

Iterate

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
class Solution {
public List<Integer> preorder(Node root) {
// root -> child1 -> child2 -> child3

List<Integer> resultList = new ArrayList<>();

Map<Node, Integer> nodeToNextChildIndexMap = new IdentityHashMap<>();

Stack<Node> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
resultList.add(root.val);
stack.push(root);
int childIndex = nodeToNextChildIndexMap.getOrDefault(root, 0);
nodeToNextChildIndexMap.put(root, childIndex + 1);
root = getChild(root, childIndex);
}

// now: root is null
Node node = stack.pop(); // 节点已经添加过,需收集该节点的其他子节点
int nextChildIndex = nodeToNextChildIndexMap.get(node);
Node nextChild = getChild(node, nextChildIndex);
if (nextChild != null) {
root = nextChild;
nodeToNextChildIndexMap.put(node, nextChildIndex + 1);
stack.push(node); // node 的子节点还未遍历完成,继续将 node 入栈
} else {
nodeToNextChildIndexMap.remove(node);
}
}

return resultList;
}

private Node getChild(Node node, int index) {
if (node.children == null || index >= node.children.size()) {
return null;
}

return node.children.get(index);
}
}

Iterate

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
class Solution {
public List<Integer> preorder(Node root) {
// root -> child1 -> child2 -> child3

List<Integer> resultList = new ArrayList<>();

Stack<Node> stack = new Stack<>();
if (root != null) {
stack.push(root);
}

while (!stack.isEmpty()) {
Node node = stack.pop();
resultList.add(node.val);

if (node.children != null) {
for (int i = node.children.size() - 1; i >= 0; i--) {
stack.push(node.children.get(i));
}
}
}

return resultList;
}
}

References

589. N-ary Tree Preorder Traversal