Skip to main content

10. Binary Tree Inorder Traversal

easyAsked at Duolingo

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 the inorder (left, node, right) traversal of its node values.

Constraints

  • 0 <= number of 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 node, recurse right.

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

Tradeoff:

2. Iterative stack

Walk left while pushing nodes; on pop, emit and step right. Avoids deep recursion stacks.

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

Duolingo-specific tips

Duolingo's skill-DAG renderer walks BSTs of unit metadata in a strict left-to-right learning order; inorder is the canonical lesson-emission pattern.

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

Practice these live with InterviewChamp.AI →