Solving Leetcode Interviews in Seconds with AI: Binary Search Tree to Greater Sum Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1038" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 original key plus the sum of all keys greater than the original key in BST. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Example 2: Input: root = [0,null,1] Output: [1,null,1] Constraints: The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val <= 100 All the values in the tree are unique. Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/
Explanation
Here's the solution to convert a BST to a Greater Tree:
Reverse Inorder Traversal: Perform a reverse inorder traversal (right, node, left) of the BST. This allows us to visit nodes in descending order of their values.
Maintain Running Sum: Keep track of a running sum of the values encountered so far during the traversal.
Update Node Values: For each node, update its value to be the current running sum, and then add the original node's value to the running sum.
Runtime Complexity: O(N), where N is the number of nodes in the BST. Storage Complexity: O(H) where H is the height of the tree (O(log N) on average, O(N) in worst case).
Code
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:
self.running_sum = 0
def reverse_inorder(node):
if not node:
return
reverse_inorder(node.right)
self.running_sum += node.val
node.val = self.running_sum
reverse_inorder(node.left)
reverse_inorder(root)
return root