9. Binary Tree Inorder Traversal
easyAsked at CheggReturn in-order values of a binary tree — Chegg uses this to check stack-based traversal on subject-taxonomy trees.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return the in-order traversal of its nodes' values (left, root, right).
Constraints
0 <= nodes <= 100-100 <= Node.val <= 100
Examples
Example 1
root = [1,null,2,3][1,3,2]Example 2
root = [][]Approaches
1. Recursive
Standard left-self-right recursion.
- Time
- O(n)
- Space
- O(h)
function inorder(node, out = []) {
if (!node) return out;
inorder(node.left, out);
out.push(node.val);
inorder(node.right, out);
return out;
}Tradeoff:
2. Iterative stack
Push lefts onto a stack; pop, visit, then descend the right subtree. Avoids recursion-depth blowups.
- Time
- O(n)
- Space
- O(h)
function inorderTraversal(root) {
const out = [], stack = [];
let node = root;
while (node || stack.length) {
while (node) { stack.push(node); node = node.left; }
node = stack.pop();
out.push(node.val);
node = node.right;
}
return out;
}Tradeoff:
Chegg-specific tips
Chegg interviewers like the iterative version because their subject-taxonomy trees can hit several thousand nested topics and recursive walks blow the JS call stack on lambda runs.
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 Chegg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →