11-line Python Pre-order solution


  • 0
    L
    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
        #use pre-order to traverse
        self.flatten(root.left)
        self.flatten(root.right)
        tail = root.left
        if tail:
            #to find the end of left child
            while tail.right:
                tail = tail.right
            #insert the left child between root and right child
            tail.right = root.right
            root.right = root.left
            #do not forget make left child to None     
            root.left = None

Log in to reply
 

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