Leetcode 538 Solution
This article provides solution to leetcode question 538 (convert-bst-to-greater-tree)
Access this page by simply typing in "lcs 538" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
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