156. Binary Tree Upside Down

Information

  • Diffculty: Medium

  • Created: 2020-01-13 00:50:24

  • Last Motified: 2020-01-13 00:50:24

  • Tags: Tree

Intuition

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.

Solution

# 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:
            return
        self._helper(node.left, node, node.right)
        node.left, node.right = right, parent