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.
- Distance between two nodes of binary tree with node values from 1 to N
- Next Greater Element
- Longest Path with Same Values in a Binary Tree
- Check if a Binary Tree (not BST) has duplicate values
- Create loops of even and odd values in a binary tree
- Transform a BST to greater sum tree
- Queries for counts of array elements with values in given range
- Sort linked list which is already sorted on absolute values
- Smallest number in BST which is greater than or equal to N
- Count greater nodes in AVL tree
- Number of nodes greater than a given value in n-ary tree
- Smallest Greater Element on Right Side
- Find next greater number with same set of digits
- Find closest greater value for every element in array
- Longest subsequence with first and last element greater than all other elements