75. Invert Binary Tree
easyAsked at WorkdayInvert a binary tree (swap left and right at every node). Workday uses this as a 5-line warmup before harder tree problems — but they grade on whether you write the recursion cleanly.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Workday loops.
- Glassdoor (2025)— Workday SDE1 phone screen.
Problem
Given the root of a binary tree, invert the tree, and return its root.
Constraints
The number of nodes in the tree is in the range [0, 100].-100 <= Node.val <= 100
Examples
Example 1
root = [4,2,7,1,3,6,9][4,7,2,9,6,3,1]Example 2
root = [2,1,3][2,3,1]Approaches
1. BFS with queue
Pop, swap children, enqueue both.
- Time
- O(n)
- Space
- O(n)
// BFS, swap children at each popTradeoff: More code than recursion. Avoids stack depth on adversarial inputs.
2. Recursive swap
Recurse on both children, then swap.
- Time
- O(n)
- Space
- O(h) stack)
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: Four lines. The recurse-then-swap order doesn't matter (recursion uses old pointers), but reading top-to-bottom is more natural.
Workday-specific tips
Workday grades for the base case (return null on empty) and pointer assignment after recursion. Mention the alternative order (swap before recurse) — both work but the post-order reads cleaner.
Common mistakes
- Forgetting the empty-tree base case.
- Swapping root.left and root.right before the recursive calls — works but confusing because you've already changed the tree.
- Returning the recursed-left value instead of root.
Follow-up questions
An interviewer at Workday may pivot to one of these next:
- Symmetric Tree (LC 101) — invert and compare.
- Iterative BFS variant.
- What if the tree has parent pointers?
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Swap before or after recursion?
Both work. After-recursion (post-order) reads like 'invert the subtrees, then swap them at this node'. Either is fine.
Why does the iconic 'fired from Google for not knowing this' story still come up?
Workday won't quiz you on this story. But it's a 5-line solution — botching it raises a flag.
Practice these live with InterviewChamp.AI
Drill Invert Binary Tree and other Workday interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →