![]() |
Given a BST, transform it into a greater sum tree where each node contains the sum of all nodes greater than that node. ![]() Table of Content Using iterative approachIn this approach we start with the rightmost node of the BST and initialize the sum to 0. We use a stack to perform iterative reverse inorder traversal. At each node, we update its value with the sum of all greater values and then update the sum with the current node’s value. We continue moving to the left child if it exists. Example: Implementation of program to Transform a BST to greater sum tree using Iterative approach.
Output 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 the BST. Auxiliary Space: O(H), where H is the height of the BST. Using recursionIn this approach we traverse BST in reverse inorder recursively. At each node, we update its value with the sum of all greater values and store the old sum in the current node. We then recur for the left subtree. Example: Implementation of program to Transform a BST to greater sum tree using recursion.
Output 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 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |