1038. Binary Search Tree to Greater Sum Tree #211
-
Topics: Given the As a reminder, a binary search tree is a tree that satisfies these constraints:
Example 1:
Example 2:
Constraints:
Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/ Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to convert a Binary Search Tree (BST) into a Greater Sum Tree (GST) where each node’s value is replaced by the sum of its original value and all the values greater than the original value in the BST. This is a variation of a well-known tree problem in which we perform a transformation on a BST. Key Points
ApproachTo solve this problem, we can leverage reverse inorder traversal. In a reverse inorder traversal, we traverse the right subtree first, then the current node, and then the left subtree. This ensures we visit nodes in descending order (from largest to smallest).
Plan
Let's implement this solution in PHP: 1038. Binary Search Tree to Greater Sum Tree <?php
/**
* @param TreeNode $root
* @return TreeNode
*/
function bstToGst($root) {
$prefix = 0;
$reversedInorder = function ($root) use (&$reversedInorder, &$prefix) {
if ($root == null)
return;
$reversedInorder($root->right);
$root->val += $prefix;
$prefix = $root->val;
$reversedInorder($root->left);
};
$reversedInorder($root);
return $root;
}
// Example 1
$root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8];
echo bstToGst($root); // Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
// Example 2
$root = [0,null,1];
echo bstToGst($root); // Output: [1,null,1]
?> Explanation:
Example WalkthroughConsider the input BST:
The final Greater Sum Tree looks like this:
Time Complexity
Output for ExampleFor the input
For the input
The solution involves a reverse inorder traversal of the BST to accumulate the sum of all greater nodes and modify the current node’s value accordingly. This approach ensures an efficient and clean solution, with time complexity proportional to the number of nodes in the tree. The solution is simple, effective, and leverages the properties of a BST to perform the required transformation. |
Beta Was this translation helpful? Give feedback.
The problem asks us to convert a Binary Search Tree (BST) into a Greater Sum Tree (GST) where each node’s value is replaced by the sum of its original value and all the values greater than the original value in the BST. This is a variation of a well-known tree problem in which we perform a transformation on a BST.
Key Points
Approach
To solve this problem, we can leverage re…