Find the largest BST subtree in a given Binary Tree | Set 3
Largest BST in a Binary Tree | Set 3
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
// C++ program to find largest BST in a Binary Tree. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ 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) { // Base cases : When tree is empty or it has one child. if (root == NULL) return {INT_MAX, INT_MIN, 0}; if (root->left == NULL && root->right == NULL) return {root->data, root->data, 1}; // Recur for left subtree and right subtrees vector< int > left = largestBSTBT(root->left); vector< int > right = largestBSTBT(root->right); // Create a return variable and initialize its size. vector< int > ans(3, 0); // If whole tree rooted under current root is BST. 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)); // Update answer for tree rooted under current 'root' ans[2] = 1 + max(left[2],right[2]); return ans; } // If whole tree is not BST, return maximum of left and right subtrees 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]; } // Driver Function int main() { /* Let us construct the following Tree 50 / \ 75 45 / 45 */ 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
// Java program to find largest BST in a Binary Tree. import java.util.*; class Main { public static int [] largestBSTBT(Node root) { // Base cases : When tree is empty or it has one // child. 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 }; // Recur for left subtree and right subtrees int [] left = largestBSTBT(root.left); int [] right = largestBSTBT(root.right); // Create a return variable and initialize its size. int [] ans = new int [ 3 ]; // If whole tree rooted under current root is BST. 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)); // Update answer for tree rooted under current // 'root' ans[ 2 ] = 1 + Math.max(left[ 2 ],right[ 2 ]); return ans; } // If whole tree is not BST, return maximum of left // and right subtrees 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 ]; } // Driver Function public static void main(String[] args) { /* Let us construct the following Tree 50 / \ 75 45 / 45 */ 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)); } } /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { int data; Node left, right; Node( int val) { this .data = val; left = null ; right = null ; } } // This code is contributed by Tapesh (tapeshdua420) |
Python3
#User function Template for 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 the size of the largest sub-tree which is also a BST return largestBst(root)[ 2 ] # Driver Code Starts import sys sys.setrecursionlimit( 1000000 ) from collections import deque # Tree Node class newNode: def __init__( self , val): self .right = None self .data = val self .left = None # Driver Code if __name__ = = '__main__' : """Let us construct the following Tree 50 / \ 75 45 / 40 """ 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#
// C# program to find largest BST in a Binary Tree. using System; /* A binary tree node has data, pointer to left child and a pointer to right child */ 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) { // Base cases : When tree is empty or it has one // child. 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 }; // Recur for left subtree and right subtrees int [] left = largestBSTBT(root.left); int [] right = largestBSTBT(root.right); // Create a return variable and initialize its size. int [] ans = new int [3]; // If whole tree rooted under current root is BST. 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)); // Update answer for tree rooted under current // 'root' ans[2] = 1 + left[2] + right[2]; return ans; } // If whole tree is not BST, return maximum of left // and right subtrees 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]; } // Driver Function public static void Main( string [] args) { /* Let us construct the following Tree 50 / \ 75 45 / 45 */ 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)); } } // This code is contributed by Tapesh (tapeshdua420) |
Javascript
// JavaScript program for above approach // A binary tree node has data, // pointer to left child and a // pointer to right child class Node { constructor(val) { this .data = val; this .left = null ; this .right = null ; } } function largestBSTBT(root) { // Base cases : When tree is empty or it has one child. if (root == null ) return [Number.MAX_VALUE, Number.MIN_VALUE, 0]; if (root.left == null && root.right == null ) return [root.data, root.data, 1]; // Recur for left subtree and right subtrees let left = largestBSTBT(root.left); let right = largestBSTBT(root.right); // Create a return variable and initialize its size. let ans = [0, 0, 0]; // If whole tree rooted under current root is BST. 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)); // Update answer for tree rooted under current 'root' ans[2] = 1 + left[2] + right[2]; return ans; } // If whole tree is not BST, return maximum of left and right subtrees 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]; } // Driver Function 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)); // This code is contributed by adityamaharshi21 |
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.
Please Login to comment...