VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bst-tree-sum-smaller-keys/

⇱ BST to a Tree with sum of all smaller keys - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

BST to a Tree with sum of all smaller keys

Last Updated : 11 Jul, 2025

Given a Binary Search Tree(BST), convert it to a Binary Tree such that every key of the original BST is changed to a key plus the sum of all smaller keys in BST.

Examples:

Input:

👁 BST-to-a-Tree-with-sum-of-all-smaller-keys

Output:

👁 BST-to-a-Tree-with-sum-of-all-smaller-keys-2


Explanation: Every key of the original BST is changed to a key plus the sum of all smaller keys in BST.

Approach:

The idea is to use recursion to traverse the tree in inorder manner while keeping a running sum of all previously visited nodes. The value of each node is updated to this running sum, which ensure that each node contains the sum of all nodes less than or equal to it.

Below is the implementation of the above approach: 


Output
1 3 10 21 36 65 105 155 

Time Complexity: O(n),  where n is the number of nodes in given Binary Tree, as it does a simple traversal of the tree.
Auxiliary Space:  O(h), where h is the height of tree.

Comment
Article Tags: