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.
- Immediate Smaller element in an N-ary Tree
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- AVL with duplicate keys
- Remove BST Keys in a given Range
- Remove BST keys outside the given range
- Construct all possible BSTs for keys 1 to N
- Print BST keys in the given range
- Find closest smaller value for every element in array
- Print BST keys in given Range | O(1) Space
- Number of elements smaller than root using preorder traversal of a BST
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Convert a given Binary tree to a tree that holds Logical OR property
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.