Share the joy
http://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
Given a Binary Tree, write a function that returns the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of whole tree.
Examples:
Input: 5 / \ 2 4 / \ 1 3 Output: 3 The following subtree is the maximum size BST subtree 2 / \ 1 3 Input: 50 / \ 30 60 / \ / \ 5 20 45 70 / \ 65 80 Output: 5 The following subtree is the maximum size BST subtree 60 / \ 45 70 / \ 65 80
Solution. If a node is a subtree, max value from left subtree should be less than node.val and min value from right subtree should be greater than node.val.
Define a Triplet for (max, min, ans). If ans is negative, it means subtree is not a BST. The largest BST in subtree is abs(ans).
Check my code on github: link