Binary Tree Upside Down Problem
Description
LeetCode Problem 156.
Given the root of a binary tree, turn the tree upside down and return the new root.
You can turn a binary tree upside down with the following steps:
- 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.

The mentioned steps are done level by level. It is guaranteed that every right node has a sibling (a left node with the same parent) and has no children.
Example 1:

Input: root = [1,2,3,4,5]
Output: [4,5,2,null,null,3,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree will be in the range
[0, 10]. 1 <= Node.val <= 10- Every right node in the tree has a sibling (a left node that shares the same parent).
- Every right node in the tree has no children.
Solution
Approach: Recursion Down the Left Spine
Every right child is a leaf with a left sibling, so the tree is really a single chain of left children (the "left spine"), and some spine nodes carry one extra right leaf. The bottom of the spine becomes the new root, and each level is flipped the same way:
- the left child
Lof a node becomes the parent, - the old right child becomes
L.left, - the node itself becomes
L.right.
Recursion does this bottom-up. If root is empty or has no left child, it is already its own upside-down tree, so return it. Otherwise flip the subtree under root.left first and keep the new root it returns. After that call, root.left is the lowest node of the flipped part and has no children yet, so we hang the old right child on its left and root on its right.
The step that is easy to forget is clearing root.left and root.right. The old root ends up as a leaf, and if its pointers stay, the tree has a cycle (root.left still points back up to its new parent).
Complexity: O(n) time, where n is the number of nodes. O(h) extra space for the recursion stack, h being the length of the left spine.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None or root.left is None:
return root
new_root = self.upsideDownBinaryTree(root.left) # the leftmost node
# root.left is now the bottom of the flipped subtree: hang root and its right child on it.
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None
return new_root