Given a Binary Search Tree(BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all smaller keys in BST.
Given a BST with N Nodes we have to convert into Binary Tree
Given above BST with N=5 Nodes. The values at Node being 9, 6, 15, 3, 21
Binary Tree after convertion
Binary Tree after convertion, the values at Node being 18, 9, 33, 3, 54
Solution: We will perform a regular Inorder traversal in which we keep track of sum of Nodes visited. Let this sum be sum. The Node which is being visited, add that key of Node to sum i.e. sum = sum + Node->key. Change the key of current Node to sum i.e. Node->key = sum.
When a BST is being traversed in inorder, for every key currently being visited, all keys that are already visited are all smaller keys.
Original BST 6 9 15 BST To Binary Tree 6 15 30
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Print BST keys in the given range
- Remove BST keys outside the given range
- Print BST keys in given Range | O(1) Space
- Remove BST Keys in a given Range
- Number of elements smaller than root using preorder traversal of a BST
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in BST)
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Transform a BST to greater sum tree
- Immediate Smaller element in an N-ary Tree
- Find all the pairs with given sum in a BST | Set 2
- Construct all possible BSTs for keys 1 to N
- A program to check if a binary tree is BST or not
- Find the largest BST subtree in a given Binary Tree | Set 1
- Largest BST in a Binary Tree | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.