Leetcode 538 Solution

This article provides solution to leetcode question 538 (convert-bst-to-greater-tree)

https://leetcode.com/problems/convert-bst-to-greater-tree

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        curr_sum = 0

        def dfs(node):
            nonlocal curr_sum

            if not node:
                return 0

            dfs(node.right)
            node.val = curr_sum = node.val + curr_sum
            dfs(node.left)

        dfs(root)
        return root