Skip to main content

9. Binary Tree Inorder Traversal

easyAsked at Spotify

Return the inorder traversal of a binary tree.

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

Problem

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

Constraints

  • 0 <= nodes <= 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. Recursive

Recurse left, push root, recurse right

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 left spine onto stack, pop and visit, then descend right. Avoids recursion-depth issues.

Time
O(n)
Space
O(h)
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;
}

Tradeoff:

Spotify-specific tips

Spotify uses tree traversals to walk hierarchical genre and playlist-folder structures, so call out the stack-based variant for production-friendly iteration.

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 Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →