Python Recursion & Reverse Inorder


  • 0
    E

    Recursion:

    def sumUp(self, node, toAdd):
            if not node: return 0
            rightSum = self.sumUp(node.right, toAdd)
            temp = node.val
            node.val += toAdd + rightSum
            leftSum = self.sumUp(node.left, node.val)
            return rightSum + leftSum + temp
    
     def convertBST(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            self.sumUp(root, 0)
            return root
    

    Reverse Inorder:

        def convertBST(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            rptr = root
            nodes, stack = [], []
            _sum = 0
            while True:
                while root:
                    stack.append(root)
                    root = root.right
                if not stack: break
                node = stack.pop()
                temp = node.val
                node.val += _sum
                _sum += temp
                root = node.left
            return rptr
    

Log in to reply
 

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