 GFG App
Open App Browser
Continue

# 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=minimum value
• ans=maximum value
• ans=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,right and return ans.

## C++14

 `// C++ program to find largest BST in a Binary Tree.` `#include ` `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 < root->data) && (right > root->data))` `    ``{` `        ``ans = min(left, min(right, root->data));` `        ``ans = max(right, max(left, root->data));` `        ``// Update answer for tree rooted under current 'root'` `        ``ans = 1 + max(left,right);` `        ``return` `ans;` `    ``}`   `    ``// If whole tree is not BST, return maximum of left and right subtrees` `    ``ans = INT_MIN;` `    ``ans = INT_MAX;` `    ``ans = max(left, right);`   `    ``return` `ans;` `}`   `int` `largestBSTBTutil(Node *root)` `{` `      ``return` `largestBSTBT(root);` `}`   `// 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:` `            ``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``;`   `        ``// If whole tree rooted under current root is BST.` `        ``if` `((left < root.data)` `            ``&& (right > root.data)) {` `            ``ans = Math.Min(` `                ``left, Math.Min(right, root.data));` `            ``ans = Math.Max(right,` `                              ``Math.Max(left, root.data));`   `            ``// Update answer for tree rooted under current` `            ``// 'root'` `            ``ans = 1 + left + right;` `            ``return` `ans;` `        ``}`   `        ``// If whole tree is not BST, return maximum of left` `        ``// and right subtrees` `        ``ans = ``int``.MinValue;` `        ``ans = ``int``.MaxValue;` `        ``ans = Math.Max(left, right);`   `        ``return` `ans;` `    ``}`   `    ``public` `static` `int` `largestBSTBTutil(Node root)` `    ``{` `        ``return` `largestBSTBT(root);` `    ``}`   `    ``// 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 < root.data && right > root.data) {` `        ``ans = Math.min(left, Math.min(right, root.data));` `        ``ans = Math.max(right, Math.max(left, root.data));` `        ``// Update answer for tree rooted under current 'root'` `        ``ans = 1 + left + right;` `        ``return` `ans;` `    ``}`   `    ``// If whole tree is not BST, return maximum of left and right subtrees` `    ``ans = Number.MIN_VALUE;` `    ``ans = Number.MAX_VALUE;` `    ``ans = Math.max(left, right);`   `    ``return` `ans;` `}`   `function` `largestBSTBTutil(root) {` `    ``return` `largestBSTBT(root);` `}`   `// 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`

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.

My Personal Notes arrow_drop_up