Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.
Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with sum 5 exists 2 \ 3 But the leaf node 8 has the maximum sum.
Approach: We traverse the tree in bottom-up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST, variable currmax to store the maximum sum of BST found till now, and a variable sum to store the sum of Left and Right subtree(which is also a BST) rooted under the current node.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the largest BST subtree in a given Binary Tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Count of elements such that its sum/difference with X also exists in the Array
- Subtree with given sum in a Binary Tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Build Binary Tree from BST such that it's level order traversal prints sorted data
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in BST)
- Find the largest Complete Subtree in a given Binary Tree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the largest Perfect Subtree in a given Binary Tree
- Duplicate subtree in Binary Tree | SET 2
- Euler Tour | Subtree Sum using Segment Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.