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
- 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
- Next Greater Element
- Transform a BST to greater sum tree
- Smallest subarray with sum greater than a given value
- Possible to form a triangle from array values
- 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
- Smallest number in BST which is greater than or equal to N
- Count of nodes that are greater than Ancestors
- Count greater nodes in AVL tree
- Create loops of even and odd values in a binary tree
- Check if a Binary Tree (not BST) has duplicate values