Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node. For example, consider the following BST.
50 / \ 30 70 / \ / \ 20 40 60 80 The above tree should be modified to following 260 / \ 330 150 / \ / \ 350 300 210 80
A simple method for solving this is to find sum of all greater values for every node. This method would take O(n^2) time.
We can do it using a single traversal. The idea is to use following BST property. If we do reverse Inorder traversal of BST, we get all nodes in decreasing order. We do reverse Inorder traversal and keep track of the sum of all nodes visited so far, we add this sum to every node.
350 330 300 260 210 150 80
Time Complexity: O(n) where n is number of nodes in the given BST.
As a side note, we can also use reverse Inorder traversal to find kth largest element in a BST.
This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Largest number possible by arranging node values at each level
- Distance between two nodes of binary tree with node values from 1 to N
- Swap Kth node from beginning with Kth node from end in a Linked List
- Check whether a node is leaf node or not for multiple queries
- Find farthest node from each node in Tree
- Next Greater Element
- Count pairs in BST with sum greater than K
- Smallest subarray with sum greater than a given value
- Transform a BST to greater sum tree
- Count of nodes that are greater than Ancestors
- Smallest number in BST which is greater than or equal to N
- Smallest Greater Element on Right Side
- Count greater nodes in AVL tree
- Number of nodes greater than a given value in n-ary tree
- Print all pairs from two BSTs whose sum is greater than the given value