Skip to main content

10. Binary Tree Inorder Traversal

easyAsked at Gojek

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

  • The number of nodes is in [0, 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

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 with stack

Push lefts onto a stack until null, pop and emit, then move right. Avoids recursion depth limits on skewed trees.

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

Gojek-specific tips

Gojek dispatchers use tree structures for region partition and zone hierarchies, so a clean iterative traversal that scales beyond the recursion limit looks intentional.

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

Practice these live with InterviewChamp.AI →