Python with stack - Using Preorder


  • 0
    S
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            if root:
                stack, llist = [root], None
                while stack:
                    node = stack.pop()
                    tleft = node.left
                    tright = node.right
                    node.left = None
                    if not llist:
                        llist = node
                    else:
                        llist.right = node
                        llist = llist.right
                    if tright:
                        stack.append(tright)
                    if tleft:
                        stack.append(tleft)
                root = llist
    

Log in to reply
 

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