Python non-recursive solution using stack


  • 0
    M
    class Solution(object):
        def flatten(self, root):
            stack = []
            while root:
                if root.right:
                    stack.append(root.right)
                    # stack right child
                if root.left:
                    root.right = root.left
                    # move left to right
                    root.left = None
                    # abort left pointer
                    root = root.right
                else:
                    if stack:
                        node = stack.pop()
                        root.right = node
                        root = node
                    else:
                        root = None
    

Log in to reply
 

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