Python Iterative


  • 0
    M
        def convertBST(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if not root:
                return root
            
            stack, visited = [root], [root.val]
            while stack:
                node = stack.pop()
                if node.left:
                    stack.append(node.left)
                    visited.append(node.left.val)
                if node.right:
                    stack.append(node.right)
                    visited.append(node.right.val)
                    
            visited.sort()
            stack = [root]
    
            while stack:
                node = stack.pop()
                node.val = sum(visited[visited.index(node.val):])
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
            
            return root
    

Log in to reply
 

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