I have recently started learning computer science and Java coding and came across Traversal techniques. I am writing a Java code using Stack. I have been with this issue and couldn't find any solution. Is there anyway we can implement Post Order traversal using only one stack (without any extra data structure or extra space) ?
I have tried doing it and here is my code.
class node {
int data;
node left, right;
node(int val){
data = val;
left = right = null;
}
}
public class binaryt {
public static void postorder(node root) {
node current = root;
Stack<node> st = new Stack<>();
System.out.println();
System.out.print("Post-order : ");
while(current!=null) {
st.push(current);
current = current.left;
}
while(!st.empty()) {
current = st.pop();
if(current.right==null) {
System.out.print(current.data+" ");
current = null;
}
else {
st.push(current);
current = current.right;
while(current!=null) {
st.push(current);
current = current.left;
}
}
}
}
public static void main(String[] args) {
node root=null;
root = new node(12);
root.left = new node(8);
root.left.left = new node(2);
root.left.right = new node(9);
root.right= new node(16);
root.right.left= new node(13);
root.right.right= new node(18);
postorder(root);
}
}
I am unable to find what's wrong with the code as it is going in infinite loop. If anyone could help me, that would be huge favor. Thank you so much.