Binary Tree Upside Down — LeetCode 156 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBinary Tree
Problem
#156
Reading time
3 min

The problem

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.

Example

Input
root = [1,2,3,4,5]
Output
[4,5,2,null,null,3,1]

Python solution

Python
# 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)
        root.left.right = root
        root.left.left = root.right
        root.left = None
        root.right = None
        return new_root

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 156. Binary Tree Upside Down is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 156. Binary Tree Upside Down?
LeetCode 156. Binary Tree Upside Down is rated Medium on LeetCode.
What is the time complexity of LeetCode 156. Binary Tree Upside Down?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 156. Binary Tree Upside Down?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 156. Binary Tree Upside Down cover?
LeetCode 156. Binary Tree Upside Down is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
Is LeetCode 156. Binary Tree Upside Down a premium problem?
Yes. LeetCode 156. Binary Tree Upside Down is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview