KatInterview

156. Binary Tree Upside Down

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to restructure a binary tree into an "upside-down" version. The transformation rules are applied locally: the original left child becomes the new root of a subtree, the original root becomes its new right child, and the original right child becomes its new left child. This process is repeated for each node along the original tree's left spine.

Solution

Binary Tree Upside Down in 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]:
        # Base case: If the root is None or we've reached the leftmost node.
        # The leftmost node will become the new root.
        if not root or not root.left:
            return root

        # Recursively find the new root, which is the original leftmost node.
        new_root = self.upsideDownBinaryTree(root.left)
        
        # In the post-order step of recursion, rewire the pointers.
        # The original left child's new right child is the original root.
        root.left.right = root
        # The original left child's new left child is the original right child.
        root.left.left = root.right
        
        # Break the old links from the original root to prevent cycles.
        root.left = None
        root.right = None
        
        # Return the new root found at the deepest recursion level.
        return new_root

Binary Tree Upside Down in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        // Base case: if the root is null or it's the end of the left spine.
        // The leftmost node becomes the new root.
        if (root == null || root.left == null) {
            return root;
        }

        // Recurse down the left spine. The leftmost node will be returned as the new root.
        TreeNode newRoot = upsideDownBinaryTree(root.left);

        // Rewire pointers in the post-order step.
        // root.left is the new parent of root.
        // root becomes the new right child of its original left child.
        root.left.right = root;
        // root.right becomes the new left child of its original left child.
        root.left.left = root.right;
        
        // Disconnect original root's children to avoid cycles.
        root.left = null;
        root.right = null;

        // Return the new root, which was found at the bottom of the left spine.
        return newRoot;
    }
}

Binary Tree Upside Down in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        // Base case: If the tree is empty or we've reached the leftmost node.
        // The leftmost node will become the new root.
        if (!root || !root->left) {
            return root;
        }

        // Recursively call for the left child. The call will return the new root.
        TreeNode* newRoot = upsideDownBinaryTree(root->left);

        // Perform the rewiring in the post-order step of the recursion.
        // The original root's left child becomes the new parent.
        // The original root becomes the new right child of its original left child.
        root->left->right = root;
        // The original root's right child becomes the new left child.
        root->left->left = root->right;

        // Sever the old connections from the original root to prevent cycles.
        root->left = nullptr;
        root->right = nullptr;

        // Return the new root found at the deepest level of recursion.
        return newRoot;
    }
};

Binary Tree Upside Down in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function upsideDownBinaryTree(root: TreeNode | null): TreeNode | null {
    // Base case: if the root is null or it's the end of the left spine.
    // The leftmost node becomes the new root.
    if (root === null || root.left === null) {
        return root;
    }

    // Recurse down the left spine. The leftmost node will be returned as the new root.
    const newRoot = upsideDownBinaryTree(root.left);
    
    // Rewire pointers in the post-order step.
    // The original left child becomes the new parent.
    // `root` becomes its new right child.
    root.left.right = root;
    // `root.right` becomes its new left child.
    root.left.left = root.right;
    
    // Sever old connections to avoid cycles.
    root.left = null;
    root.right = null;

    // Return the new root passed up from the base case.
    return newRoot;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.