Transform a BST to greater sum treeWhat is BST?The acronym "BST" in Python stands for "Binary Search Tree." A common data structure for organizing and storing a collection of elements, such as numbers, in a way that enables effective searching, insertion, deletion, and traversal operations is called a binary search tree. Because each node in the tree only has two children, the left child and the right child, it is known as a "binary" search tree. Transforming a BST into greater sum tree:You can use a reversed in-order traversal of the tree to convert a Binary Search Tree (BST) into a Greater Sum Tree. A reversed in-order traversal involves visiting the right subtree, the current node, and the left subtree in that order. You update the values of each node with the running sum while maintaining a running total of the nodes you have already traversed. Method 1:The tree need not be a BST to use this technique. The steps are listed below:
This takes O(n2) Time Complexity. Method 2 (Using only one traversal):We can discover an O(n) solution by taking advantage of the fact that the tree is a BST. It is intended to travel through BST in reverse order. We get keys in decreasing order from a BST's reverse inorder traversal. We visit every greater node of a node before visiting it. We keep track of the sum of keys, which is the total of all keys greater than the key of the current node, while traversing. Code: Output: Inorder Traversal of the given tree: 1 2 7 11 15 29 35 40 Inorder Traversal of the transformed tree: > 5 139 137 130 119 104 75 40 0 5 Explanation: Simply put, this code defines a binary tree and a function to create a "sum tree" from the values of its nodes. A sum tree is a binary tree in which the value of each node is changed to the total of all higher values in the tree. The code employs a recursive method to carry out this transformation.
Time Complexity: O(n) because only a simple traversal of the binary tree is performed, where n is the number of nodes in the binary tree. Auxiliary Space: O(h), where h represents the height of the given binary tree as a result of recursion. |