Skip to main content

10. Binary Tree Inorder Traversal

easyAsked at Coursera

Return inorder traversal of a binary tree — Coursera tests recursive-vs-iterative tradeoffs in a course-tree walking context.

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

Problem

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

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. Recursion

Walk left, push node, walk 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 stack

Push left chain, pop and visit, descend right.

Time
O(n)
Space
O(h)
function inorder(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:

Coursera-specific tips

Coursera reviewers value showing the iterative variant even after the recursive one — they ship traversal in browser environments where stack depth has bitten them before.

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

Practice these live with InterviewChamp.AI →