-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNaryPostOrder.java
More file actions
49 lines (44 loc) · 1.11 KB
/
NaryPostOrder.java
File metadata and controls
49 lines (44 loc) · 1.11 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
package Tree;
import java.util.*;
/**
* Author - archit.s
* Date - 23/08/18
* Time - 10:58 AM
*/
public class NaryPostOrder {
//Iterative Solution
public List<Integer> postorder(Node root) {
if (root == null) return Collections.emptyList();
Stack<Node> stack = new Stack<>();
Deque<Integer> vals = new ArrayDeque<>();
stack.push(root);
while (!stack.empty()) {
Node n = stack.pop();
vals.push(n.val);
if (n.children.size() > 0) {
for (Node node : n.children) {
stack.push(node);
}
}
}
return new ArrayList<>(vals);
}
// Recursive Solution
// private void post(Node root, List<Integer> l){
// if(root == null){
// return;
// }
//
// for(int i=0;i<root.children.size();i++){
// post(root.children.get(i), l);
// }
// l.add(root.val);
// }
//
// public List<Integer> postorder(Node root) {
// List<Integer> l = new ArrayList<>();
// post(root, l);
//
// return l;
// }
}