-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnaryTreePostorder.java
More file actions
54 lines (50 loc) · 1.74 KB
/
naryTreePostorder.java
File metadata and controls
54 lines (50 loc) · 1.74 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
import java.util.*;
public class naryTreePostorder {
// method 1: 还是掌握这种方法吧!
public List<Integer> postorder(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
Stack<Node> stack = new Stack<>();
stack.add(root);
while(!stack.isEmpty()) {
root = stack.pop();
list.add(root.val);
for(Node node: root.children)
stack.add(node);
}
Collections.reverse(list);
return list;
}
// method 2
public List<Integer> postorder2(Node root) {
List<Integer> res = new ArrayList<>();
Stack<Node> stack = new Stack<>();
// store the index of current node in its parent list.
Stack<Integer> index = new Stack<>();
Node move = root;
while(!stack.isEmpty() || move != null){
if(move != null){
stack.push(move);
res.add(move.val);
// 一直往右走
int size = move.children.size();
move = size > 0 ? move.children.get(size-1) : null;
index.push(size-1);
}else{
// push 进去的index是child相对于p(arent) node而言
Node p = stack.pop();
int idx = index.pop();
// 注意这里因为是n-array tree。找到了左边一位的child之后还要再push回去。
if(idx - 1 >= 0){
move = p.children.get(idx - 1);
index.push(idx-1);
stack.push(p);
}else{
move = null;
}
}
}
Collections.reverse(res);
return res;
}
}