LC 1038 0538 [M] [M] Binary Search Tree to Greater Sum Tree, Convert BST to Greater Tree - ALawliet/algorithms GitHub Wiki
we want to calculate the suffix sum, so by the time we get to a node we have the running sum from the number greater than it
# 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:
suffixsum = 0
def bstToGst(self, root):
if root.right:
self.bstToGst(root.right)
print(root.val)
root.val = root.val + self.suffixsum
self.suffixsum = root.val
if root.left:
self.bstToGst(root.left)
return root
# 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:
suffixsum = 0
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root: return None
if root.right:
self.convertBST(root.right)
print(root.val)
root.val = root.val + self.suffixsum
self.suffixsum = root.val
if root.left:
self.convertBST(root.left)
return root