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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Subtree with given sum in a Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Duplicate subtree in Binary Tree | SET 2
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Find the largest BST subtree in a given Binary Tree | Set 1
- 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 2
- Check if a binary tree is subtree of another binary tree | Set 1
- Even size subtree in n-ary tree
- Queries for DFS of a subtree in a tree
- Subtree of all nodes in a tree using DFS
- Find largest subtree sum in a tree
- Euler Tour | Subtree Sum using Segment Tree
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find GCD of each subtree of a given node in an N-ary Tree for Q queries
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Count of distinct colors in a subtree of a Colored Tree with given min frequency for Q queries
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.