8-line recursive Python


  • 4

    Three rules:

    1. root's right node becomes the left node of the left node of root
    2. root becomes the right node of root's left node
    3. above rules apply on the left edge and return left node along the path.
    class Solution(object):
        def upsideDownBinaryTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if not root or (not root.left and not root.right):
                return root
            left = self.upsideDownBinaryTree(root.left)
            root.left.left = root.right
            root.left.right = root
            root.left = None
            root.right = None
            return left
    

  • 0
    J

    This is a very clean solution!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.