python codes


  • 0
    C

    Just to share my codes. Maybe not inplace.
    Solution one (Used stack)

    class Solution(object):
        def flatten(self, root):
            stack, cur = [], root
            while stack or cur is not None:
                if cur.right is not None:
                    stack.append(cur.right)
                if cur.left is not None:
                    cur.right = cur.left
                    cur.left = None
                elif stack:
                    cur.right = stack.pop()
                    
                cur = cur.right
    

    solution 2, used left to store data instead of stack

    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            left, cur = None, root
            while (left is not None) or (cur is not None):
                if cur.right is not None:
                    if left is None:
                        left = cur.right
                    else:
                        oldLeft = left
                        left = p = cur.right
                        
                        while p.right is not None:
                            p = p.right
                            
                        p.right = oldLeft
                if cur.left is not None:
                    cur.right = cur.left
                    cur.left = None
                elif left is not None:
                    cur.right = left
                    left = None
                cur = cur.right
    

Log in to reply
 

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