# Largest BST in a Binary Tree | Set 2

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 of whole tree.

Examples:

```Input:
5
/
2    4
/
1    3

Output: 3
The following subtree is the
maximum size BST subtree
2
/
1    3

Input:
50
/
30       60
/       /
5   20   45    70
/
65    80
Output: 5
The following subtree is the
maximum size BST subtree
60
/
45    70
/
65    80
```

We have discussed a two methods in below post.
Find the largest BST subtree in a given Binary Tree | Set 1

In this post a different O(n) solution is discussed. This solution is simpler than the solutions discussed above and works in O(n) time.

The idea is based on method 3 of check if a binary tree is BST article.

A Tree is BST if following is true for every node x.

1. The largest value in left subtree (of x) is smaller than value of x.
2. The smallest value in right subtree (of x) is greater than value of x.

We traverse tree in bottom up manner. For every traversed node, we return maximum and minimum values in subtree rooted with it. If any node follows above properties and size of

## C++

 `// 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; ` `}; ` ` `  `/* Helper function that allocates a new ` `node with the given data and NULL left ` `and right pointers. */` `struct` `Node* newNode(``int` `data) ` `{ ` `    ``struct` `Node* node = ``new` `Node; ` `    ``node->data = data; ` `    ``node->left = node->right = NULL; ` ` `  `    ``return``(node); ` `} ` ` `  `// Information to be returned by every ` `// node in bottom up traversal. ` `struct` `Info ` `{ ` `    ``int` `sz; ``// Size of subtree ` `    ``int` `max; ``// Min value in subtree ` `    ``int` `min; ``// Max value in subtree ` `    ``int` `ans; ``// Size of largest BST which ` `    ``// is subtree of current node ` `    ``bool` `isBST; ``// If subtree is BST ` `}; ` ` `  `// Returns Information about subtree. The ` `// Information also includes size of largest ` `// subtree which is a BST. ` `Info largestBSTBT(Node* root) ` `{ ` `    ``// Base cases : When tree is empty or it has ` `    ``// one child. ` `    ``if` `(root == NULL) ` `        ``return` `{0, INT_MIN, INT_MAX, 0, ``true``}; ` `    ``if` `(root->left == NULL && root->right == NULL) ` `        ``return` `{1, root->data, root->data, 1, ``true``}; ` ` `  `    ``// Recur for left subtree and right subtrees ` `    ``Info l = largestBSTBT(root->left); ` `    ``Info r = largestBSTBT(root->right); ` ` `  `    ``// Create a return variable and initialize its ` `    ``// size. ` `    ``Info ret; ` `    ``ret.sz = (1 + l.sz + r.sz); ` ` `  `    ``// If whole tree rooted under current root is ` `    ``// BST. ` `    ``if` `(l.isBST && r.isBST && l.max < root->data && ` `            ``r.min > root->data) ` `    ``{ ` `        ``ret.min = min(l.min, min(r.min, root->data)); ` `        ``ret.max = max(r.max, max(l.max, root->data)); ` ` `  `        ``// Update answer for tree rooted under ` `        ``// current 'root' ` `        ``ret.ans = ret.sz; ` `        ``ret.isBST = ``true``; ` ` `  `        ``return` `ret; ` `    ``} ` ` `  `    ``// If whole tree is not BST, return maximum ` `    ``// of left and right subtrees ` `    ``ret.ans = max(l.ans, r.ans); ` `    ``ret.isBST = ``false``; ` ` `  `    ``return` `ret; ` `} ` ` `  `/* Driver program to test above functions*/` `int` `main() ` `{ ` `    ``/* Let us construct the following Tree ` `        ``60 ` `       ``/  ` `      ``65  70 ` `     ``/ ` `    ``50 */` ` `  `    ``struct` `Node *root = newNode(60); ` `    ``root->left = newNode(65); ` `    ``root->right = newNode(70); ` `    ``root->left->left = newNode(50); ` `    ``printf``(````" Size of the largest BST is %d "````, ` `           ``largestBSTBT(root).ans); ` `    ``return` `0; ` `} ` ` `  `// This code is contributed by Vivek Garg in a ` `// comment on below set 1. ` `// www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/ `

## Python3

 `# Python program to find largest  ` `# BST in a Binary Tree. ` ` `  `INT_MIN ``=` `-``2147483648` `INT_MAX ``=` `2147483647` ` `  `# Helper function that allocates a new  ` `# node with the given data and None left  ` `# and right pointers.  ` `class` `newNode:  ` ` `  `    ``# Constructor to create a new node  ` `    ``def` `__init__(``self``, data):  ` `        ``self``.data ``=` `data  ` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None` ` `  `# Returns Information about subtree. The  ` `# Information also includes size of largest  ` `# subtree which is a BST ` `def` `largestBSTBT(root): ` `     `  `# Base cases : When tree is empty or it has  ` `    ``# one child.  ` `    ``if` `(root ``=``=` `None``): ` `        ``return` `0``, INT_MIN, INT_MAX, ``0``, ``True` `    ``if` `(root.left ``=``=` `None` `and` `root.right ``=``=` `None``) : ` `        ``return` `1``, root.data, root.data, ``1``, ``True` ` `  `    ``# Recur for left subtree and right subtrees  ` `    ``l ``=` `largestBSTBT(root.left)  ` `    ``r ``=` `largestBSTBT(root.right)  ` ` `  `    ``# Create a return variable and initialize its  ` `    ``# size.  ` `    ``ret ``=` `[``0``, ``0``, ``0``, ``0``, ``0``]  ` `    ``ret[``0``] ``=` `(``1` `+` `l[``0``] ``+` `r[``0``])  ` ` `  `    ``# If whole tree rooted under current root is  ` `    ``# BST.  ` `    ``if` `(l[``4``] ``and` `r[``4``] ``and` `l[``1``] <  ` `        ``root.data ``and` `r[``2``] > root.data) : ` `     `  `        ``ret[``2``] ``=` `min``(l[``2``], ``min``(r[``2``], root.data))  ` `        ``ret[``1``] ``=` `max``(r[``1``], ``max``(l[``1``], root.data))  ` ` `  `        ``# Update answer for tree rooted under  ` `        ``# current 'root'  ` `        ``ret[``3``] ``=` `ret[``0``]  ` `        ``ret[``4``] ``=` `True` ` `  `        ``return` `ret  ` `     `  ` `  `    ``# If whole tree is not BST, return maximum  ` `    ``# of left and right subtrees  ` `    ``ret[``3``] ``=` `max``(l[``3``], r[``3``])  ` `    ``ret[``4``] ``=` `False` ` `  `    ``return` `ret ` ` `  `# Driver Code  ` `if` `__name__ ``=``=` `'__main__'``:  ` `     `  `    ``"""Let us construct the following Tree ` `        ``60  ` `        ``/   ` `        ``65 70  ` `    ``/  ` `    ``50 """` `    ``root ``=` `newNode(``60``)  ` `    ``root.left ``=` `newNode(``65``)  ` `    ``root.right ``=` `newNode(``70``)  ` `    ``root.left.left ``=` `newNode(``50``) ` `    ``print``(``"Size of the largest BST is"``, ` `                    ``largestBSTBT(root)[``3``])  ` `                             `  `# This code is contributed ` `# Shubham Singh(SHUBHAMSINGH10) `

Output:

```Size of largest BST is 2
```

Time Complexity : O(n)

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org

code

load comments