Binary Tree Inorder Traversal explained
An in-order traversal of a binary tree visits the left subtree, then the node, then the right subtree. Recursion does it in three lines; interviewers usually ask for the iterative version, which pushes nodes on a stack while diving left, pops one, records it, and then moves to its right child. Both take O(n) time and O(h) memory, and Morris traversal brings the memory to O(1) by temporarily rewiring pointers.
By Evin JohnPublished 8 min read
The task, reworded
Given the root of a binary tree, list its values in in-order: everything in a node's left subtree comes first, then the node itself, then everything in its right subtree, applied at every level. An empty tree gives an empty list.
6 4
/ \ / \
2 9 8 2
/ \ \ \ /
1 4 12 1 5
/
3
in-order: 1 2 3 4 6 9 12 in-order: 8 1 4 5 2The left tree is a binary search tree, so its in-order list comes out sorted. The right tree is not, and its in-order list is just the left-node-right reading of whatever is there. Both outputs were produced by the code below.
Why such a basic question gets asked
The recursive answer is trivial, so the question is really about the iterative one. Can you simulate recursion with a stack, and can you explain what the stack holds at any moment? That skill transfers directly to iterators over trees, to validating search trees, to finding the k-th smallest value and to many interview questions that are traversals in disguise. Morris traversal is a common follow-up for strong candidates.
Recursive version
def in_order_values(root):
out = []
def visit(node):
if node is None:
return
visit(node.left)
out.append(node.val)
visit(node.right)
visit(root)
return outThe order of the three lines is the whole definition: move the append before both calls and you get preorder, after both and you get postorder. Its weakness is depth. A tree shaped like a long chain has height n, and a chain around a thousand nodes deep can already hit Python's default recursion limit.
Iterative version with an explicit stack
Think about what recursion does when it reaches a node. It cannot record the node yet, because the left subtree comes first, so it remembers the node and goes left. That memory is the call stack. Do the same by hand: from the current node, push and move left until there is no left child. The top of the stack is now the leftmost unvisited node, so pop it and record it. Its left side is done, so continue from its right child, which may start another dive to the left.
def in_order_iterative(root):
out, stack = [], []
node = root
while node is not None or stack:
while node is not None: # dive left, remembering the path
stack.append(node)
node = node.left
node = stack.pop()
out.append(node.val)
node = node.right
return outfunction inOrderIterative(root) {
const out = [];
const stack = [];
let node = root;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
out.push(node.val);
node = node.right;
}
return out;
}What the stack holds
At any moment the stack holds the nodes whose left subtree you are still inside, from the root downward. On the search tree above, the first dive pushes 6, 2 and 1. Popping 1 records it; it has no right child, so 2 is popped and recorded, then the walk moves to 4 and dives to 3. The stack is never deeper than the height of the tree, which is the O(h) space bound.
Morris traversal: no stack at all
The stack exists so you can climb back up after finishing a left subtree. Morris traversal stores that way back inside the tree. Before going left from a node, find its in-order predecessor, the rightmost node of its left subtree, and point that predecessor's empty right pointer back at the node. Later, when the walk follows that thread back up, it recognizes the thread, removes it, records the node and moves right.
def in_order_morris(root):
out = []
node = root
while node is not None:
if node.left is None:
out.append(node.val)
node = node.right
continue
# find node's in-order predecessor in its left subtree
pred = node.left
while pred.right is not None and pred.right is not node:
pred = pred.right
if pred.right is None:
pred.right = node # leave a thread back to node
node = node.left
else:
pred.right = None # second visit: remove the thread
out.append(node.val)
node = node.right
return outIt still runs in O(n) total even with the inner predecessor search, because each edge of the tree is walked a constant number of times: at most twice to find the predecessor and twice by the main walk. The catches are worth stating. The tree is modified during the walk, so it is unsafe if another thread reads it at the same time, and an exception halfway through would leave threads behind.
Complexity
| Version | Time | Extra space | Changes the tree? |
|---|---|---|---|
| Recursion | O(n) | O(h) call stack | No |
| Explicit stack | O(n) | O(h) | No |
| Morris threading | O(n) | O(1) | Temporarily, then restored |
Edge cases
- Empty tree: return an empty list without touching the stack.
- A single node: a list with one value.
- A chain leaning left: the stack grows to n before the first pop, the worst case for space.
- A chain leaning right: the stack never holds more than one node.
- Duplicate values: order is by position, not by value, so duplicates are simply listed where they sit.
Common mistakes
- Popping before the left dive finishes, which records nodes in preorder by accident.
- Writing the loop condition as only while stack, which stops too early when the stack empties but a right subtree is still waiting in the current node.
- Pushing both children up front, the preorder habit, which does not produce in-order.
- In Morris traversal, forgetting to remove the thread, which leaves the tree permanently changed and can make later walks loop.
Follow-up questions
- Build an iterator with next and has-next. Keep the explicit stack as the iterator's state; each next call pops one node and dives left from its right child. Average O(1) per call, O(h) memory.
- Check that a tree is a valid search tree. The in-order values must strictly increase, which is one of the two methods in Validate Binary Search Tree.
- Return the k-th smallest value in a search tree. Stop the iterative walk after k pops.
- Do preorder and postorder iteratively. Preorder pushes right then left; postorder is easiest as a reversed node, right, left walk.
Explaining it out loud
Fictional example
- Candidate
- Recursively it's left, node, right. To do it iteratively, I'll keep the nodes whose left side I'm still exploring on my own stack.
- Candidate
- From the current node I push and go left until I can't. The top of the stack is then the next node in order, so I pop it, record it, and continue from its right child.
- Candidate
- Every node is pushed and popped once, so it's linear, and the stack never gets deeper than the tree. If memory is tight, Morris traversal threads predecessors back to their nodes for O(1) space.
Related walkthroughs
Validate Binary Search Tree uses this exact walk to check ordering. Flatten Binary Tree to Linked List rewires right pointers in a way that closely resembles Morris threading, but for preorder. Binary Tree Zigzag Level Order Traversal visits the tree level by level instead of depth first. More on the coding problems hub.
Natively for tree practice
On a Mac or Windows computer, Natively can read a tree problem from a screenshot during practice, and you can ask it to show what the stack holds after each step, the part most people cannot answer cleanly. It records a transcript and notes of the mock session so you can reread your explanation afterward. Find out more on the AI interview assistant page.
Questions people ask
How do you do an inorder traversal iteratively?
Push nodes while moving left from the current node. When you cannot go further left, pop the top node, record its value, and continue from its right child. Repeat until the current node is empty and the stack is empty.
What is the time and space complexity of inorder traversal?
O(n) time for every version. Recursion and the explicit stack use O(h) space for a tree of height h; Morris traversal uses O(1) extra space.
Why does inorder traversal of a BST give sorted values?
In a binary search tree everything in a node's left subtree is smaller and everything in its right subtree is larger, so visiting left, node, right lists the values in increasing order.
What is Morris inorder traversal?
A method that temporarily points each node's in-order predecessor back to the node, so the walk can return without a stack. It removes each thread on the second visit, leaving the tree unchanged.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
