My Super Simple Stupid Solution Using Python


  • 0
    Z

    It's obviously that the result is a form of the order follow tree's pre-order travel.

    So let's keep the travel order to complete a super simple stupid solution.

    The execute time is about 60~70ms.

    class Solution:
        
        def __init__(self):
            self.nodeArr = [] # keep travel order of nodes
        
        # @param {TreeNode} node
        def travel(self, node):
            if not node:
                return
            self.nodeArr.append(node)
            self.travel(node.left)
            self.travel(node.right)
        
        # @param {TreeNode} root
        # @return {void} Do not return anything, modify root in-place instead.
        def flatten(self, root):
            self.travel(root)
            
            for node in self.nodeArr:
                node.left = None
                node.right = None
            
            nodeNum = len(self.nodeArr)
            for i in range(0,nodeNum - 1):
                parent = self.nodeArr[i]
                child = self.nodeArr[i+1]
                parent.right = child

Log in to reply
 

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