Find the largest BST subtree in a given Binary Tree | Set 3
Last Updated :
19 Jul, 2023
Method 3 (Shorter, Smarter and More Efficient)
In this section, a different O(n) solution is discussed. This solution is simpler than the solutions discussed in Set-1 and Set-2 and works in O(n) time. In this method, we do not need to check explicitly if the binary tree is BST. A Tree is BST if the following is true for every node x.
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 will use a array/list ans :
• ans[0]=minimum value
• ans[1]=maximum value
• ans[2]=size of current largest BST
Algorithm:
1. If root==None:
return INT_MAX,INT_MIN,0
2. If (root.left==None and root.right==None):
return root.data,root.data,1
3. Initialize ans=[0,0,0]
4. Check if the largest value of the left subtree is less than the value of the root node and the smallest value of the right subtree is greater than the value of the root node, if this holds true, update the ans accordingly and return ans.
5. If 4 is false, we will assign values as IMIN,IMAX, max(left[2],right[2] and return ans.
C++14
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node( int val)
{
this ->data = val;
left = NULL;
right = NULL;
}
};
vector< int > largestBSTBT(Node* root)
{
if (root == NULL)
return {INT_MAX, INT_MIN, 0};
if (root->left == NULL && root->right == NULL)
return {root->data, root->data, 1};
vector< int > left = largestBSTBT(root->left);
vector< int > right = largestBSTBT(root->right);
vector< int > ans(3, 0);
if ((left[1] < root->data) && (right[0] > root->data))
{
ans[0] = min(left[0], min(right[0], root->data));
ans[1] = max(right[1], max(left[1], root->data));
ans[2] = 1 + left[2] + right[2];
return ans;
}
ans[0] = INT_MIN;
ans[1] = INT_MAX;
ans[2] = max(left[2], right[2]);
return ans;
}
int largestBSTBTutil(Node *root)
{
return largestBSTBT(root)[2];
}
int main() {
struct Node *root = new Node(50);
root->left = new Node(75);
root->right = new Node(45);
root->left->left = new Node(40);
printf ( " Size of the largest BST is %d\n" , largestBSTBTutil(root));
return 0;
}
|
Java
import java.util.*;
class Main {
public static int [] largestBSTBT(Node root)
{
if (root == null )
return new int [] { Integer.MAX_VALUE,
Integer.MIN_VALUE, 0 };
if (root.left == null && root.right == null )
return new int [] { root.data, root.data, 1 };
int [] left = largestBSTBT(root.left);
int [] right = largestBSTBT(root.right);
int [] ans = new int [ 3 ];
if ((left[ 1 ] < root.data)
&& (right[ 0 ] > root.data)) {
ans[ 0 ] = Math.min(
left[ 0 ], Math.min(right[ 0 ], root.data));
ans[ 1 ] = Math.max(right[ 1 ],
Math.max(left[ 1 ], root.data));
ans[ 2 ] = 1 + left[ 2 ] + right[ 2 ];
return ans;
}
ans[ 0 ] = Integer.MIN_VALUE;
ans[ 1 ] = Integer.MAX_VALUE;
ans[ 2 ] = Math.max(left[ 2 ], right[ 2 ]);
return ans;
}
public static int largestBSTBTutil(Node root)
{
return largestBSTBT(root)[ 2 ];
}
public static void main(String[] args)
{
Node root = new Node( 50 );
root.left = new Node( 75 );
root.right = new Node( 45 );
root.left.left = new Node( 40 );
System.out.println( "Size of the largest BST is "
+ largestBSTBTutil(root));
}
}
class Node {
int data;
Node left, right;
Node( int val)
{
this .data = val;
left = null ;
right = null ;
}
}
|
Python3
IMIN = - 2147483648
IMAX = 2147483647
def largestBst(root):
if root = = None :
return IMAX,IMIN, 0
if (root.left = = None and root.right = = None ):
return root.data,root.data, 1
left = largestBst(root.left)
right = largestBst(root.right)
ans = [ 0 , 0 , 0 ]
if left[ 1 ]<root.data and right[ 0 ]>root.data:
ans[ 0 ] = min (left[ 0 ],right[ 0 ],root.data)
ans[ 1 ] = max (right[ 1 ],left[ 1 ],root.data)
ans[ 2 ] = 1 + left[ 2 ] + right[ 2 ]
return ans
ans[ 0 ] = IMIN
ans[ 1 ] = IMAX
ans[ 2 ] = max (left[ 2 ],right[ 2 ])
return ans
def largestBstUtil(root):
return largestBst(root)[ 2 ]
import sys
sys.setrecursionlimit( 1000000 )
from collections import deque
class newNode:
def __init__( self , val):
self .right = None
self .data = val
self .left = None
if __name__ = = '__main__' :
root = newNode( 50 )
root.left = newNode( 75 )
root.right = newNode( 45 )
root.left.left = newNode( 40 )
print ( "Size of the largest BST is" ,largestBstUtil(root))
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int val)
{
this .data = val;
left = null ;
right = null ;
}
}
public class GFG {
public static int [] largestBSTBT(Node root)
{
if (root == null )
return new int [] { int .MaxValue, int .MinValue,
0 };
if (root.left == null && root.right == null )
return new int [] { root.data, root.data, 1 };
int [] left = largestBSTBT(root.left);
int [] right = largestBSTBT(root.right);
int [] ans = new int [3];
if ((left[1] < root.data)
&& (right[0] > root.data)) {
ans[0] = Math.Min(
left[0], Math.Min(right[0], root.data));
ans[1] = Math.Max(right[1],
Math.Max(left[1], root.data));
ans[2] = 1 + left[2] + right[2];
return ans;
}
ans[0] = int .MinValue;
ans[1] = int .MaxValue;
ans[2] = Math.Max(left[2], right[2]);
return ans;
}
public static int largestBSTBTutil(Node root)
{
return largestBSTBT(root)[2];
}
public static void Main( string [] args)
{
Node root = new Node(50);
root.left = new Node(75);
root.right = new Node(45);
root.left.left = new Node(40);
Console.WriteLine( "Size of the largest BST is "
+ largestBSTBTutil(root));
}
}
|
Javascript
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
function largestBSTBT(root) {
if (root == null ) return [Number.MAX_VALUE, Number.MIN_VALUE, 0];
if (root.left == null && root.right == null ) return [root.data, root.data, 1];
let left = largestBSTBT(root.left);
let right = largestBSTBT(root.right);
let ans = [0, 0, 0];
if (left[1] < root.data && right[0] > root.data) {
ans[0] = Math.min(left[0], Math.min(right[0], root.data));
ans[1] = Math.max(right[1], Math.max(left[1], root.data));
ans[2] = 1 + left[2] + right[2];
return ans;
}
ans[0] = Number.MIN_VALUE;
ans[1] = Number.MAX_VALUE;
ans[2] = Math.max(left[2], right[2]);
return ans;
}
function largestBSTBTutil(root) {
return largestBSTBT(root)[2];
}
let root = new Node(50);
root.left = new Node(75);
root.right = new Node(45);
root.left.left = new Node(40);
console.log( "Size of the largest BST is" ,largestBSTBTutil(root));
|
Output
Size of the largest BST is 2
Time Complexity: O(n),
Auxiliary Space: O(n)
Here n is the number of nodes in the given Binary Tree.
Share your thoughts in the comments
Please Login to comment...