590. N-ary Tree Postorder 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> postorder(Node root) {
// child3 -> child2 -> child1 -> root

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

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

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

resultList.add(node.val);
}
}

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

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

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

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

Node node = stack.pop();
int nextChildIndex = nodeToNextChildIndexMap.get(node);
Node nextChild = getChild(node, nextChildIndex);
if (nextChild != null && nextChild != prev) {
// 进入右子树,但不能重复进入
root = nextChild;
nodeToNextChildIndexMap.put(node, nextChildIndex + 1);
stack.push(node); // node 节点为 root, 还需继续处理,所以需要入栈
} else {
// node is root
resultList.add(node.val);
prev = node;
}
}

return resultList;
}

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

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

References

590. N-ary Tree Postorder Traversal