Binary Tree Inorder Traversal
Difficulty: Easy · Pattern: Trees & BST · LeetCode #94
Given the root of a binary tree, return the inorder traversal of its values (left subtree, node, right subtree). Try the iterative version too.
Examples
text
[1,null,2,3] → [1,3,2]
[] → []
[1] → [1]Hints
- The recursive version is three lines. The iterative version is what interviewers really ask for.
- Use an explicit stack: push nodes while going left. When you can't go further, pop, visit, and step right.
Approach
Iterative inorder simulates the call stack:
text
cur = root
while cur or stack:
while cur: # dive left, remembering the path
stack.push(cur); cur = cur.left
cur = stack.pop() # leftmost unvisited node
visit(cur)
cur = cur.right # then its right subtreeOn a BST, inorder gives the values in sorted order. That fact powers Kth Smallest, Validate BST and the BST Iterator.
Morris traversal does it in O(1) extra space by temporarily threading each predecessor's right pointer back to the current node. It's worth knowing it exists.
Complexity
Time: O(n). Space: O(h) for the stack (O(1) with Morris).
Python solution
def inorderTraversal(root):
out, stack, cur = [], [], root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
out.append(cur.val)
cur = cur.right
return outJavaScript solution
function inorderTraversal(root) {
const out = [], stack = [];
let cur = root;
while (cur || stack.length) {
while (cur) { stack.push(cur); cur = cur.left; }
cur = stack.pop();
out.push(cur.val);
cur = cur.right;
}
return out;
}