10. Binary Tree Inorder Traversal
easyAsked at GitHubReturn the inorder traversal of a binary tree's node values — GitHub's lead-in to traversing the parent-DAG of a commit history in chronological order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return the inorder traversal of its nodes' values. Solve recursively, then convert to iterative using an explicit stack.
Constraints
Nodes in [0, 100]-100 <= Node.val <= 100
Examples
Example 1
root = [1,null,2,3][1,3,2]Example 2
root = [][]Approaches
1. Recursive
Standard left-root-right recursion.
- 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
Push lefts onto stack, pop and visit, then dive right. Avoids stack-overflow on deep trees and matches how commit-graph walkers iterate parents lazily.
- Time
- O(n)
- Space
- O(h)
function inorderTraversal(root) {
const stack = [], out = [];
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;
}Tradeoff:
GitHub-specific tips
GitHub asks 'now do it iteratively' — they care about explicit-stack mastery because the commit-graph walker can't risk JS recursion limits on deep repos.
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 GitHub interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →