Skip to content
LC-0538 Medium LeetCode

538. Convert BST to Greater Tree

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 70% Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(h)

class Solution(object):
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def convertBSTHelper(root, cur_sum):
            if not root:
                return cur_sum

            if root.right:
                cur_sum = convertBSTHelper(root.right, cur_sum)
            cur_sum += root.val
            root.val = cur_sum
            if root.left:
                cur_sum = convertBSTHelper(root.left, cur_sum)
            return cur_sum

        convertBSTHelper(root, 0)
        return root

Solution from kamyu104/LeetCode-Solutions · MIT