Skip to main content

9. Binary Tree Inorder Traversal

easyAsked at Tesla

Return the inorder traversal of a binary tree's node values.

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

Problem

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

Constraints

  • 0 <= node count <= 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(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; on pop, visit and descend right. Avoids recursion limits in embedded code.

Time
O(n)
Space
O(h)
function inorderIter(root) {
  const out = [], st = [];
  let cur = root;
  while (cur || st.length) {
    while (cur) { st.push(cur); cur = cur.left; }
    cur = st.pop();
    out.push(cur.val);
    cur = cur.right;
  }
  return out;
}

Tradeoff:

Tesla-specific tips

Tesla embedded engineers prefer the iterative form because deep recursion can blow a small ECU stack — show you can convert any tree walk to an explicit stack.

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

Practice these live with InterviewChamp.AI →