Skip to main content

9. Binary Tree Inorder Traversal

easyAsked at Yelp

Return the inorder traversal of a binary tree — Yelp treats this as the warmup for sorted enumeration over the BST that backs nearby-business range queries.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, return the inorder (left-root-right) traversal of its nodes' values as a flat array.

Constraints

  • Number of nodes is in [0, 100]
  • -100 <= Node.val <= 100

Examples

Example 1

Input
root = [1,null,2,3]
Output
[1,3,2]

Example 2

Input
root = []
Output
[]

Approaches

1. Recursion

Recurse left, push root, recurse 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 with explicit stack

Push left spine, pop and visit, walk right.

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:

Yelp-specific tips

Yelp likes the iterative form because it avoids recursion-depth surprises and ports cleanly to streaming BST scans over their indexed-business store.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Binary Tree Inorder Traversal and other Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →