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 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:
- Subtree with given sum in a Binary Tree
- Duplicate subtree in Binary Tree | SET 2
- Find the largest BST subtree in a given Binary Tree | Set 1
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the largest Complete Subtree in a given Binary Tree
- Find the largest Perfect Subtree in a given Binary Tree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- 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
- Queries for DFS of a subtree in a tree
- Subtree of all nodes in a tree using DFS
- Even size subtree in n-ary tree
- Find largest subtree sum in a tree
- 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.