Transform a BST to greater sum tree
Given a BST, transform it into a greater sum tree where each node contains the sum of all nodes greater than that node.
We strongly recommend minimizing the browser and try this yourself first.
Method 1 (Naïve):
This method doesn’t require the tree to be a BST. Following are the steps.
- Traverse node by node(Inorder, preorder, etc.)
- For each node find all the nodes greater than that of the current node, sum the values. Store all these sums.
- Replace each node value with their corresponding sum by traversing in the same order as in Step 1.
This takes O(n2) Time Complexity.
Method 2 (Using only one traversal):
By leveraging the fact that the tree is a BST, we can find an O(n) solution. The idea is to traverse BST in reverse inorder. Reverse inorder traversal of a BST gives us keys in decreasing order. Before visiting a node, we visit all greater nodes of that node. While traversing we keep track of the sum of keys which is the sum of all the keys greater than the key of the current node.
Inorder Traversal of given tree 1 2 7 11 15 29 35 40 Inorder Traversal of transformed tree 139 137 130 119 104 75 40 0
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 given Binary Tree due to Recursion
Please Login to comment...