Clean Python Solution with Stack (The Greatest)

  • 0
    class Solution(object):
        def upsideDownBinaryTree(self, root):
            if root == None:
                return None
            stack = []
            # append left nodes to stack
            while root != None:
                root = root.left
            # initialize new root
            new_root = stack.pop()
            runner = new_root
            while len(stack) != 0:
                # pop off parent node, need to clear left and right for cyclical case
                parent = stack.pop()
                parent.left = None
                runner.right = parent
                runner.left = parent.right
                # clear right after, becauses we needed to use it to set runner.left
                parent.right = None
                runner = runner.right
            return new_root

Log in to reply

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