Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the sum of the keys greater than or equal to the original key in BST.
To solve this problem, we can perform a Reverse Inorder Traversal of the BST:
By traversing the tree in reverse inorder fashion, we can keep a cumulative sum of all the nodes we have visited so far and update the current node’s value to this cumulative sum.
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: TreeNode) -> TreeNode:
"""
Convert the BST to a Greater Tree.
:param root: TreeNode - the root of the BST
:return: TreeNode - the root of the modified Greater Tree
"""
self.cumulative_sum = 0
def reverse_inorder(node):
if not node:
return
# Traverse the right subtree first
reverse_inorder(node.right)
# Visit the node
self.cumulative_sum += node.val
node.val = self.cumulative_sum
# Traverse the left subtree
reverse_inorder(node.left)
reverse_inorder(root)
return root
This completes the solution for converting a given BST to a Greater Tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?