VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-bst-to-a-binary-tree/

⇱ Convert a BST to a Binary Tree such that sum of all greater keys is added to every key - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert a BST to a Binary Tree such that sum of all greater keys is added to every key

Last Updated : 29 Mar, 2023

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 greater keys in BST. 
Examples: 

Input: Root of following BST
 5
 / \
 2 13

Output: The given BST is converted to following Binary Tree
 18
 / \
 20 13

Method 1:

Solution: Do reverse In order traversal. Keep track of the sum of nodes visited so far. Let this sum be sum. For every node currently being visited, first add the key of this node to sum, i.e. sum = sum + node->key. Then change the key of current node to sum, i.e., node->key = sum
When a BST is being traversed in reverse In order, for every key currently being visited, all keys that are already visited are all greater keys.
Implementation:


Output
Inorder traversal of the given tree
2 5 13 
Inorder traversal of the modified tree
20 18 13 

Time Complexity: O(n) where n is the number of nodes in given Binary Search Tree.

The space complexity is O(H), where H is the height of the tree, due to the recursive call stack.

Method 2:

The below method uses the technique of Iteration with the Stack.

Approach:

  1. First, we initialize an empty stack and set the current node to the root.
  2. Then, so long as there are unvisited nodes in the stack or the node does not point to null, we push all of the nodes along the path to the rightmost leaf onto the stack.
  3. . Next, we visit the node on the top of our stack and consider its left subtree.
  4. Eventually, our stack is empty and the node points to the left null child of the tree's minimum value node, so the loop terminates.

Below is the implementation of the above approach:


Output
58 56 51 44 36 27 15 

Time Complexity: O(n) , n is no.of Node in a BST.

Auxiliary Space: O(n). Stack is used for storing data.

Comment
Article Tags: