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.
Examples:
Input:
Output: 3 The following subtree is the maximum size BST subtree
Input:
Output: 5 The following subtree is the maximum size BST subtree
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
C++14
#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Returns a vector of size 3: {min, max, size of largest BST}// Vector {INT_MAX, INT_MIN, 0} is returned for an empty treevector<int>largestBSTUtil(Node*root){if(!root)return{INT_MAX,INT_MIN,0};if(!root->left&&!root->right)return{root->data,root->data,1};vector<int>left=largestBSTUtil(root->left);vector<int>right=largestBSTUtil(root->right);vector<int>ans(3);// If the current subtree rooted at root is a BSTif(left[1]<root->data&&right[0]>root->data){ans[0]=min(left[0],root->data);ans[1]=max(right[1],root->data);ans[2]=left[2]+right[2]+1;returnans;}// If the subtree is not a BSTans[0]=INT_MIN;ans[1]=INT_MAX;ans[2]=max(left[2],right[2]);returnans;}// Function to find the size of the largest BST// in a binary treeintlargestBst(Node*root){returnlargestBSTUtil(root)[2];}intmain(){Node*root=newNode(50);root->left=newNode(75);root->right=newNode(45);root->left->left=newNode(40);cout<<largestBst(root)<<endl;return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGfG{// Returns an array of size 3: {min, max, size of largest BST}// Array {Integer.MAX_VALUE, Integer.MIN_VALUE, 0} is // returned for an empty treepublicstaticint[]largestBSTUtil(Noderoot){if(root==null){returnnewint[]{Integer.MAX_VALUE,Integer.MIN_VALUE,0};}if(root.left==null&&root.right==null){returnnewint[]{root.data,root.data,1};}int[]left=largestBSTUtil(root.left);int[]right=largestBSTUtil(root.right);int[]ans=newint[3];// If the current subtree rooted at root is a BSTif(left[1]<root.data&&right[0]>root.data){ans[0]=Math.min(left[0],root.data);ans[1]=Math.max(right[1],root.data);ans[2]=left[2]+right[2]+1;returnans;}// If the subtree is not a BSTans[0]=Integer.MIN_VALUE;ans[1]=Integer.MAX_VALUE;ans[2]=Math.max(left[2],right[2]);returnans;}// Function to find the size of the largest BST// in a binary treepublicstaticintlargestBst(Noderoot){returnlargestBSTUtil(root)[2];}publicstaticvoidmain(String[]args){Noderoot=newNode(50);root.left=newNode(75);root.right=newNode(45);root.left.left=newNode(40);System.out.println(largestBst(root));}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Returns a list of size 3: [min, max, size of largest BST]# List [float('inf'), float('-inf'), 0] is returned for an empty treedeflargestBSTUtil(root):ifnotroot:return[float('inf'),float('-inf'),0]ifnotroot.leftandnotroot.right:return[root.data,root.data,1]left=largestBSTUtil(root.left)right=largestBSTUtil(root.right)ans=[0,0,0]# If the current subtree rooted at root is a BSTifleft[1]<root.data<right[0]:ans[0]=min(left[0],root.data)ans[1]=max(right[1],root.data)ans[2]=left[2]+right[2]+1returnans# If the subtree is not a BSTans[0]=float('-inf')ans[1]=float('inf')ans[2]=max(left[2],right[2])returnans# Function to find the size of the largest BST in a binary treedeflargestBst(root):returnlargestBSTUtil(root)[2]# Driver program to test the above functionsif__name__=="__main__":root=Node(50)root.left=Node(75)root.right=Node(45)root.left.left=Node(40)print(largestBst(root))
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classProgram{// Returns an array of size 3: [min, max, size of largest BST]// Array {int.MaxValue, int.MinValue, 0} is returned for an empty treepublicstaticint[]largestBSTUtil(Noderoot){if(root==null)returnnewint[]{int.MaxValue,int.MinValue,0};if(root.left==null&&root.right==null)returnnewint[]{root.data,root.data,1};int[]left=largestBSTUtil(root.left);int[]right=largestBSTUtil(root.right);int[]ans=newint[3];// If the current subtree rooted at root is a BSTif(left[1]<root.data&&root.data<right[0]){ans[0]=Math.Min(left[0],root.data);ans[1]=Math.Max(right[1],root.data);ans[2]=left[2]+right[2]+1;returnans;}// If the subtree is not a BSTans[0]=int.MinValue;ans[1]=int.MaxValue;ans[2]=Math.Max(left[2],right[2]);returnans;}// Function to find the size of the largest BST in a binary treepublicstaticintlargestBst(Noderoot){returnlargestBSTUtil(root)[2];}// Driver program to test the above functionspublicstaticvoidMain(){Noderoot=newNode(50);root.left=newNode(75);root.right=newNode(45);root.left.left=newNode(40);Console.WriteLine(largestBst(root));// Output: 1}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Returns an array of size 3: [min, max, size of largest BST]// Array [Infinity, -Infinity, 0] is returned for an empty treefunctionlargestBSTUtil(root){if(!root){return[Infinity,-Infinity,0];}if(!root.left&&!root.right){return[root.data,root.data,1];}letleft=largestBSTUtil(root.left);letright=largestBSTUtil(root.right);letans=[0,0,0];// If the current subtree rooted at root is a BSTif(left[1]<root.data&&root.data<right[0]){ans[0]=Math.min(left[0],root.data);ans[1]=Math.max(right[1],root.data);ans[2]=left[2]+right[2]+1;returnans;}// If the subtree is not a BSTans[0]=-Infinity;ans[1]=Infinity;ans[2]=Math.max(left[2],right[2]);returnans;}// Function to find the size of the largest BST in a binary treefunctionlargestBst(root){returnlargestBSTUtil(root)[2];}// Driver program to test the above functionsletroot=newNode(50);root.left=newNode(75);root.right=newNode(45);root.left.left=newNode(40);console.log(largestBst(root));// Output: 1
Output
2
Time Complexity: O(n), Auxiliary Space: O(n)
Here n is the number of nodes in the given Binary Tree.