Python recursive swapping solution (commented)


  • 0
    N
    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            if not root:
                return None
            root = self.as_list(root)
    
        def as_list(self, node):
            # I'll change the node so I'm keeping this for later return value
            ref = node
    
            if not node:
                return None
            if self.is_leaf(node):
                return node
    
            # Recursive swapping: Using the right to save the list of the left 
            # nodes, while keeping the nodes of the right in a temp
            temp = self.as_list(node.right)
            node.right = self.as_list(node.left)
    
            # Connect the end of the (new) right nodes list to the (new) list built
            # from the left nodes
            while node.right:
                node = node.right
            node.right = temp
    
            # Making sure that the new "list" node does not have a left node
            ref.left = None
            return ref
    
    
        def is_leaf(self, node):
            return not (node.left or node.right)
    

Log in to reply
 

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