Skip to main content

8. Invert Binary Tree

easyAsked at Autodesk

Mirror a binary tree by swapping left and right children at every node.

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

Problem

Given the root of a binary tree, invert the tree by swapping every node's left and right subtree, and return the root of the resulting tree.

Constraints

  • 0 <= node count <= 100
  • -100 <= node value <= 100

Examples

Example 1

Input
root=[4,2,7,1,3,6,9]
Output
[4,7,2,9,6,3,1]

Example 2

Input
root=[]
Output
[]

Approaches

1. Rebuild from arrays

Serialize to a level-order array, reverse children per level, deserialize back.

Time
O(n)
Space
O(n)
// flatten level order, swap children pair by pair, rebuild tree
// verbose and allocation-heavy

Tradeoff:

2. Recursive swap

Recurse into both children, then swap them. Simple and uses only the recursion stack.

Time
O(n)
Space
O(h)
function invertTree(root) {
  if (!root) return null;
  const left = invertTree(root.left);
  const right = invertTree(root.right);
  root.left = right;
  root.right = left;
  return root;
}

Tradeoff:

Autodesk-specific tips

Mirror operations on hierarchies map directly to Autodesk's symmetric-modeling tools (Maya/Fusion 360), so they appreciate clean recursive intent.

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

Practice these live with InterviewChamp.AI →