Advertisement
darekfive

Post Order Traversal Iterator

Mar 1st, 2025
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. class PostorderIterator {
  4.     private Stack<Node> stack = new Stack<>();
  5.     private Node prevProcessed = null;
  6.  
  7.     public PostorderIterator(Node root) {
  8.         pushLeftSubtree(root);
  9.     }
  10.  
  11.     private void pushLeftSubtree(Node node) {
  12.         while (node != null) {
  13.             stack.push(node);
  14.             node = node.left;
  15.         }
  16.     }
  17.  
  18.     public int next() {
  19.         if (!hasNext()) {
  20.             return -1;
  21.         }
  22.  
  23.         while (!stack.isEmpty()) {
  24.             Node curr = stack.peek();
  25.             // If there's no right child OR right child has already been processed
  26.             if (curr.right == null || curr.right == prevProcessed) {
  27.                 stack.pop();
  28.                 prevProcessed = curr;
  29.                 return curr.val; // Corrected return statement
  30.             }
  31.  
  32.             // Process right subtree
  33.             pushLeftSubtree(curr.right);
  34.         }
  35.  
  36.         return -1; // Should never reach here if hasNext() is checked before calling next()
  37.     }
  38.  
  39.     public boolean hasNext() {
  40.         return !stack.isEmpty();
  41.     }
  42. }
  43.  
  44. class Node {
  45.     int val;
  46.     Node left, right;
  47.  
  48.     public Node(int val) {
  49.         this.val = val;
  50.         this.left = null;
  51.         this.right = null;
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement