Binary Tree Upside Down

Problem Id: 156 Difficulty: Medium Tag: Tree


Draw the process on a paper and you will get the solution easily.

The upside down is actually done on the left path of the tree.


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode:
        if root is None:
            return None
        new_root = root
        while new_root.left:
            new_root = new_root.left

        self._helper(root, None, None)
        return new_root

    def _helper(self, node, parent, right):
        if node is None:
        self._helper(node.left, node, node.right)
        node.left, node.right = right, parent