Skip to main content

9. Binary Tree Inorder Traversal

easyAsked at GoDaddy

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 traversal (left-root-right) of its nodes' 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, visit root, recurse right.

Time
O(n)
Space
O(h)
function inorder(r,out=[]){ if(!r) return out; inorder(r.left,out); out.push(r.val); inorder(r.right,out); return out; }

Tradeoff:

2. Iterative with stack

Use a manual stack: push lefts, pop+visit, jump right.

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

Tradeoff:

GoDaddy-specific tips

GoDaddy uses tree traversal to test how you would walk a hosting account's nested resource tree (account -> domain -> subdomain -> cert) for billing rollups.

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

Practice these live with InterviewChamp.AI →