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 (number of nodes) of the whole tree.
Prerequisite : Validate BST (Minimum and Maximum Value Approach)
We have discussed Naive and Efficient Approaches in Largest BST in a Binary Tree . Here we are going to discuss a simpler implementation of the efficient solution that returns an array of size 3 instead of creating a separate class.
We use the below same idea
1. The largest value in the left subtree (of x) is smaller than the value of x. 2. The smallest value in the right subtree (of x) is greater than the value of x.
So, we will just check if the largest value of the left subtree is less than the value of the root node and the smallest value of right subtree is greater than the value of root node.
We use a array/list of size 3 :
• ans[0]=minimum value • ans[1]=maximum value • ans[2]=size of current largest BST
Output
2
Time Complexity: O(n), Auxiliary Space: O(n)
Here n is the number of nodes in the given Binary Tree.