-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
43 lines (39 loc) · 1.14 KB
/
Copy pathsolution.java
File metadata and controls
43 lines (39 loc) · 1.14 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
/*
class Node {
int data;
Node left, right;
Node(int val){
data = val;
left = right = null;
}
}
*/
import java.util.ArrayList;
import java.util.Stack;
class Solution {
public ArrayList<Integer> postOrder(Node root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) return result;
Stack<Node> st = new Stack<>();
Node curr = root;
Node lastVisited = null;
while (curr != null || !st.isEmpty()) {
if (curr != null) {
st.push(curr);
curr = curr.left;
} else {
Node peekNode = st.peek();
// If right child exists and hasn't been visited, move to right child
if (peekNode.right != null && lastVisited != peekNode.right) {
curr = peekNode.right;
} else {
// Visit the node
result.add(peekNode.data);
lastVisited = peekNode;
st.pop();
}
}
}
return result;
}
}