-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBinaryTreePostOrderTraversalWithStack.java
67 lines (51 loc) · 1.6 KB
/
BinaryTreePostOrderTraversalWithStack.java
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
65
66
67
package problems.leetcode;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
/**
* https://leetcode.com/problems/binary-tree-postorder-traversal/
*/
public class BinaryTreePostOrderTraversalWithStack {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private static class VisitedNode {
TreeNode node;
boolean childrenVisited;
VisitedNode(TreeNode node, boolean childrenVisited) {
this.node = node;
this.childrenVisited = childrenVisited;
}
}
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
List<Integer> visited = new ArrayList<>();
Deque<VisitedNode> stack = new ArrayDeque<>();
stack.addLast(new VisitedNode(root, false));
while (stack.size() > 0) {
VisitedNode v = stack.removeLast();
if (v.childrenVisited) {
visited.add(v.node.val);
} else {
stack.addLast(new VisitedNode(v.node, true));
// we will pop left child first...
if (v.node.right != null) {
stack.addLast(new VisitedNode(v.node.right, false));
}
if (v.node.left != null) {
stack.addLast(new VisitedNode(v.node.left, false));
}
}
}
return visited;
}
}