Python recursive solution


  • 0
    J
    class Solution(object):
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
    
            self.helper(root)
            
        def helper(self,root):
    
            if root is None:
                return None, None
            
            node = root
                
            leftup, leftbottom = self.helper(root.left)
            rightup, rightbottom = self.helper(root.right)
            
            if leftup:
                node.right = leftup
                node.left = None
    
            if leftbottom:
                leftbottom.right = rightup
                leftbottom.left = None
            else:
                leftbottom = node
    
            if not rightbottom:
                rightbottom = leftbottom
            
            return node, rightbottom

Log in to reply
 

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