9. Binary Tree Inorder Traversal
easyAsked at DigitalOceanReturn the inorder traversal of a binary tree — DigitalOcean uses this to test tree-walk fluency that mirrors traversing a region/zone/rack hierarchy for billing rollups.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return the inorder traversal of its nodes' values. Inorder means left subtree, node, right subtree.
Constraints
0 <= number of nodes <= 100-100 <= node.val <= 100
Examples
Example 1
root=[1,null,2,3][1,3,2]Example 2
root=[][]Approaches
1. Recursive
DFS left, push node, DFS right.
- Time
- O(n)
- Space
- O(h)
function inorder(root, out=[]) {
if (!root) return out;
inorder(root.left, out);
out.push(root.val);
inorder(root.right, out);
return out;
}Tradeoff:
2. Iterative stack
Use a stack: push lefts, pop and emit, then move to right child.
- Time
- O(n)
- Space
- O(h)
function inorder(root) {
const out = [], stack = [];
let curr = root;
while (curr || stack.length) {
while (curr) { stack.push(curr); curr = curr.left; }
curr = stack.pop();
out.push(curr.val);
curr = curr.right;
}
return out;
}Tradeoff:
DigitalOcean-specific tips
DigitalOcean prefers the iterative version because their infra topology graphs can be deep enough to blow recursion stacks during multi-region traversal.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Binary Tree Inorder Traversal and other DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →