Traversals with a stack
25 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Iterative traversals use an explicit stack to traverse binary trees safely without recursive call stack limits.
Simulating the Call Stack with an Explicit Stack
An explicit stack does the job of the recursive call stack. Push the root, then repeat: pop a node, visit it, push its right child, then push its left child.
Iterative preorder with a stack
Step 1 of 6
- 1
Example 1 · Iterative Preorder Traversal with Stack
import java.util.ArrayDeque;import java.util.Deque;
public class IterativePreorderDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static void iterativePreorder(TreeNode root) { if (root == null) return; Deque<TreeNode> stack = new ArrayDeque<>(); stack.push(root);
while (!stack.isEmpty()) { TreeNode curr = stack.pop(); System.out.print(curr.val + " "); if (curr.right != null) stack.push(curr.right); if (curr.left != null) stack.push(curr.left); } }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5);
System.out.print("Iterative preorder: "); iterativePreorder(root); System.out.println(); }}Iterative preorder: 1 2 4 5 3
What this code does
- Pushes the right child before the left child so left pops first.
- Processes nodes in Root-Left-Right order without using recursion.
Recursive traversals rely on the Java runtime call stack to remember parent nodes. When a tree has a depth of tens of thousands of nodes, recursive calls exhaust stack memory. An explicit stack allocated on the heap circumvents thread call stack limitations. We push and pop TreeNode references to simulate recursive execution manually.
For iterative preorder traversal, we start by pushing the root onto the stack. While the stack is not empty, we pop the top node and process its value. Then, we push its right child first, followed by its left child. Pushing right before left ensures the left child pops first, matching preorder sequence. Trace iterative preorder on tree with root 1, left 2, right 3: Push 1. Stack: [1]. Pop 1, print 1. Push right 3, push left 2. Stack: [3, 2]. Pop 2, print 2. Node 2 has no children. Stack: [3]. Pop 3, print 3. Node 3 has no children. Output is 1 2 3.
Order of execution
Order of one stack step
Tap the steps in the order the loop runs them.
Iterative Inorder and Postorder Algorithms
Iterative inorder keeps pushing left children, pops one node to visit it, then moves to its right child. Postorder is harder because a parent must wait for both children.
Example 2 · Iterative Inorder Traversal with Stack
import java.util.ArrayDeque;import java.util.Deque;
public class IterativeInorderDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static void iterativeInorder(TreeNode root) { Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode curr = root;
while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); System.out.print(curr.val + " "); curr = curr.right; } }
public static void main(String[] args) { TreeNode root = new TreeNode(4); root.left = new TreeNode(2); root.right = new TreeNode(5); root.left.left = new TreeNode(1); root.left.right = new TreeNode(3);
System.out.print("Iterative inorder: "); iterativeInorder(root); System.out.println(); }}Iterative inorder: 1 2 3 4 5
What this code does
- Pushes nodes along the left boundary until reaching null.
- Pops to process the node, then traverses into its right child.
Example 3 · Iterative Postorder Traversal with Two Stacks
import java.util.ArrayDeque;import java.util.Deque;
public class IterativePostorderDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }
public static void iterativePostorder(TreeNode root) { if (root == null) return; Deque<TreeNode> s1 = new ArrayDeque<>(); Deque<TreeNode> s2 = new ArrayDeque<>(); s1.push(root);
while (!s1.isEmpty()) { TreeNode curr = s1.pop(); s2.push(curr); if (curr.left != null) s1.push(curr.left); if (curr.right != null) s1.push(curr.right); }
while (!s2.isEmpty()) { System.out.print(s2.pop().val + " "); } }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4);
System.out.print("Iterative postorder: "); iterativePostorder(root); System.out.println(); }}Iterative postorder: 4 2 3 1
What this code does
- Stack 1 processes nodes in Root-Right-Left sequence onto stack 2.
- Popping from stack 2 outputs the correct Left-Right-Root postorder.
Iterative inorder traversal requires descending leftwards as far as possible. We maintain a current pointer curr starting at the root. While curr is not null or the stack is non-empty, push curr and advance left. When curr hits null, we pop the top node, process it, and move curr = curr.right.
Iterative postorder is more challenging because parents are processed after both children. A straightforward approach uses two stacks. Stack 1 processes nodes in Root-Right-Left order and pushes them onto Stack 2. Stack 2 reverses this sequence into Left-Right-Root order upon popping. Alternatively, postorder can use a single stack and track the last visited node. If the top node has no right child or its right child was just visited, we process it. Otherwise, we advance into the right subtree. Both techniques run in O(n) time and O(h) space.
Morris Traversal: O(1) Auxiliary Space
Morris traversal is an inorder walk that uses O(1) extra space: no recursion and no stack. It temporarily links a node's predecessor back to it.
TreeNode curr = root;while (curr != null) { if (curr.left == null) { // nothing on the left: visit, go right System.out.print(curr.val + " "); curr = curr.right; } else { TreeNode pred = curr.left; // predecessor: rightmost node of the left subtree while (pred.right != null && pred.right != curr) pred = pred.right; if (pred.right == null) { pred.right = curr; curr = curr.left; } // make the thread, go left else { pred.right = null; System.out.print(curr.val + " "); curr = curr.right; } // undo, visit }}Morris traversal is an inorder traversal that uses O(1) auxiliary space, with no recursion and no stack. Recursive and stack-based traversals both use O(h) auxiliary memory. Morris utilizes null pointers in leaf nodes to create temporary threads back to predecessors. Before descending left, it finds the rightmost node in the left subtree, called the predecessor.
If the predecessor's right pointer is null, it points it to the current node and moves left. If the predecessor's right pointer already points to curr, the left subtree is done. It restores the right pointer to null, processes curr, and moves right. This clever pointer threading visits all nodes in O(n) time with zero extra memory. Morris traversal temporarily mutates the tree structure during execution. However, it cleanly restores all original null pointers before terminating. It represents an elegant theoretical approach for memory-constrained embedded environments. For general software, standard stack-based traversals remain preferred for simplicity.
Next step
Check your understanding
10 quick questions