Skip to main content

10. Binary Tree Inorder Traversal

easyAsked at Brex

Return the inorder (left, root, right) 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 the inorder traversal of its nodes' values as a list. Inorder means visit left subtree, then root, then right subtree.

Constraints

  • Number of nodes in the tree is in range [0, 100]
  • -100 <= node value <= 100

Examples

Example 1

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

Example 2

Input
root = []
Output
[]

Approaches

1. Recursive

Recurse into left, push root, recurse into right.

Time
O(n)
Space
O(h)
const out=[];
(function dfs(n){if(!n)return;dfs(n.left);out.push(n.val);dfs(n.right);})(root);
return out;

Tradeoff:

2. Iterative with stack

Push left spine, pop and emit, then move to right child. Avoids recursion blowup on skewed trees.

Time
O(n)
Space
O(h)
function inorderTraversal(root) {
  const out = [];
  const 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:

Brex-specific tips

Brex maps tree traversal to walking nested approval-chain trees (manager > director > VP), so be ready to extend it to early-exit when a node already denied the spend.

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

Practice these live with InterviewChamp.AI →