1038. Binary Search Tree to Greater Sum Tree | Leetcode Daily (POTD) 25 June 2024 | Java | Hindi

preview_player
Показать описание
"1038. Binary Search Tree to Greater Sum Tree" is a medium-level problem and the daily challenge for June 25, 2024, on LeetCode. The solution provided in the video is coded in Java, but the approach is explained using a dry-run on a whiteboard. This makes the video accessible and beneficial for individuals with different programming backgrounds, as it focuses on the underlying logic rather than language-specific details.

### Intuition

When converting a Binary Search Tree (BST) to a Greater Sum Tree (GST), the goal is to transform each node's value to the sum of all values greater than or equal to the node's value.

One might initially think to traverse the tree in an inorder fashion (left-root-right), store the nodes in a list to sort them, and then compute the sums. However, this method uses extra space and is inefficient.

A more optimal approach involves a reverse inorder traversal (right-root-left). By traversing the tree this way, we can maintain a running sum of all nodes visited so far. For each node, we update its value to this running sum. This method is efficient and uses constant space, as it modifies the tree in place.

### Enhanced and Simplified Explanation

In this problem, we need to transform each node in the BST so that its value becomes the sum of all values greater than or equal to it. The optimal approach explained in the video uses a reverse inorder traversal. This traversal method ensures we visit nodes in descending order, allowing us to maintain a running sum and update each node's value directly. This avoids the need for extra space and makes the solution efficient.

Other problems for practice:

#leetcodejava #leetcode #dailychallenge #potd #hindi
Рекомендации по теме
Комментарии
Автор

Mam, I think this one Recursive Solution i also best. Check it once and compare the Space complexities of both solution and do let us know which one is better and why..

class Solution
{
int Sum = 0;

public TreeNode bstToGst(TreeNode root)
{
if(root == null) return root;

bstToGst(root.right);
root.val += Sum;
Sum = root.val;
bstToGst(root.left);

return root;
}

}

tejas
Автор

iska iterative solution bhi upload kardo ya fir intuition bata do, discuss section se samajh nahi aa raha

zebra-erxc
Автор

mam which is best programming language for DSA ?

raskarpratik
visit shbcf.ru