Imagine you have a binary tree that needs to be completely flipped upside down! This isn't just a simple rotation - it's a systematic transformation where each level undergoes a specific rearrangement.
Given the root of a binary tree, you need to turn the entire tree upside down and return the new root. The transformation follows these rules for each node:
The original left child becomes the new root
The original root becomes the new right child
The original right child becomes the new left child
This process is applied level by level throughout the tree. The problem guarantees that every right node has a corresponding left sibling (same parent) and that right nodes have no children, making this transformation always possible.
Example: If you have a tree like 1-2-3, after flipping it becomes a completely different structure where the leftmost bottom node becomes the new root!
Input & Output
example_1.py — Basic Tree
$Input:root = [1,2,3,4,5]
›Output:[4,5,2,null,null,3,1]
💡 Note:The original tree has root 1 with children 2,3. Node 2 has children 4,5. After flipping upside down, node 4 (leftmost leaf) becomes the new root. Node 2 becomes 4's right child, and 5 becomes 4's left child. This pattern continues up the tree.
example_2.py — Single Node
$Input:root = [1]
›Output:[1]
💡 Note:A single node tree remains unchanged when flipped upside down since there are no children to rearrange.
example_3.py — Empty Tree
$Input:root = []
›Output:[]
💡 Note:An empty tree (null root) remains empty after the upside-down transformation.
Constraints
The number of nodes in the tree is in the range [0, 1000]
-1000 ≤ Node.val ≤ 1000
Every right node has a sibling (left node with same parent) and no children
The tree structure guarantees a valid upside-down transformation is possible
G
Google 45a
Amazon 38f
Meta 32⊞
Microsoft 28
Apple 22
Binary Tree Upside Down — Solution
The optimal approach uses bottom-up recursion to transform the tree in O(n) time and O(h) space. The key insight is to process the leftmost path first, then rearrange parent-child relationships: left child becomes new root, original root becomes right child, and original right child becomes left child. This elegant solution avoids creating new nodes and works with the existing tree structure.
Common Approaches
✓
Iterative Level-by-Level Transformation
⏱️ Time: O(n²)
Space: O(n)
This approach processes the tree level by level, maintaining queues to track the transformation at each level. It's more systematic than pure recursion but still involves multiple data structures to manage the transformation process.