Leetcode 1038: Binary Search Tree to Greater Sum Tree

grid47
grid47
Exploring patterns and algorithms
Jul 26, 2024 5 min read

Given the root of a Binary Search Tree (BST), convert it into a Greater Tree where each node’s value is updated to the sum of its original value and all the values greater than it in the BST. The transformation should preserve the BST structure.
Problem
Approach
Steps
Complexity
Input: You are provided with the root of a Binary Search Tree. The nodes of the tree are distinct integers, and the task is to transform the tree as described.
Example: Input: root = [5,3,8,1,4,7,10]
Constraints:
• 1 <= number of nodes <= 100
• 0 <= Node.val <= 100
• All node values are distinct
Output: Return the root of the Greater Tree after transformation.
Example: Output: [30,36,21,36,35,26,15]
Constraints:
• The tree should be transformed such that each node's value is the sum of its original value and all greater values in the BST.
Goal: The goal is to transform the BST into a Greater Tree by accumulating the sum of all values greater than a node's value.
Steps:
• 1. Perform a reverse in-order traversal of the BST, starting from the rightmost node.
• 2. Accumulate the sum of nodes encountered during the traversal, updating each node's value.
• 3. Continue the traversal until all nodes are visited.
Goal: The number of nodes is between 1 and 100, with values between 0 and 100. The values are unique across the tree.
Steps:
• 1 <= number of nodes <= 100
• 0 <= Node.val <= 100
• All values in the tree are unique
Assumptions:
• The input tree is a valid Binary Search Tree (BST) with unique values.
Input: Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Explanation: After converting the BST to a Greater Tree, the new root tree will be [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8], where each node is updated to the sum of its original value and the values greater than it.

Input: Input: root = [0,null,1]
Explanation: After the transformation, the tree becomes [1,null,1], where the only non-zero transformation is at the root node.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus