This post is completed by 1 user
|Add to List|
Convert BST to Greater Sum Tree
Objective: Given a binary search tree (BST), convert it into a greater sum tree.
What is a greater sum tree: Greater sum tree is a tree in which every node contains the sum of all the nodes which are greater than the node. see the example below
The naive approach will be for every node, traverse the tree and find out all the nodes which are greater and update the node. This approach is fine but the only problem with this approach is the Time Complexity will be O(N^2). We can do it in one traversal.
We know that the rightmost node in the binary search tree is the biggest node among all nodes so we will start from there, (reverse in-order traversal).
- Since we are visiting the nodes in decreasing order so we need to care about maintaining the sum of the nodes visited.
- Keep a global variable that maintains the sum of the nodes visited till now.
- Before updating the node value, store it in temp, we need it later
- Updated the node value as sum ( since each node contains a sum of nodes greater than that node which means we need to exclude the node value itself).
- Update the sum as sum = sum + temp (for the next node in iteration).
- See the code for a better understanding.
2 5 7 10 12 15 20 69 64 57 47 35 20 0
- Minimum No of operations required to convert a given number to 1 - Integer Replacement Problem. Medium
- Populate Next Siblings Pointers in a Given Binary Tree OR Populate Next Right Pointers in Each Node Hard