CodeArchon

easyTreesGoogleAmazonApple

Locale Layout Inverter

A UI rendering engine flips directory trees and navigation hierarchies to support Right-to-Left (RTL) locales.

Given the root of a binary tree, invert the tree (swap left and right children recursively) and return its root.

Choose approach

4
curr
2
7
1
3
6
9
1/15
Narrationstep 1 of 15

Visit node 4. Swap its left and right descendants.

1def invertTree(root: Optional[TreeNode]) -> Optional[TreeNode]:
2 if not root:
3 return None
4 root.left, root.right = invertTree(root.right), invertTree(root.left)
5 return root
Variables
curr=4

How to think about it

  1. DFS traversal guarantees every node is visited.
  2. At each node, swap left and right subtrees.
  3. Call recursion on the new left and right subtrees.

Edge cases to catch in interview

  • Empty tree -> do nothing.
  • Single node -> already inverted.

Examples

Example 1inverted tree
{"arr":[4,2,7,1,3,6,9]}
Example 2[]
{"arr":[]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed