Given a binary tree, find the size of the largest BST (Binary Search Tree) in it.

The largest BST in the following binary tree is formed by the subtree rooted at node 15, having size 3:

Largest BST

Practice this problem

A simple solution is to traverse the binary tree in a preorder fashion and for each encountered node, check whether the subtree rooted at the node is a BST or not. If the subtree is a BST, calculate and return the subtree’s size rooted at the node. Otherwise, return the maximum size BST returned by the left and right subtrees.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The size of the largest BST is 3

Java


Download  Run Code

Output:

The size of the largest BST is 3

Python


Download  Run Code

Output:

The size of the largest BST is 3

The time complexity of this approach is O(n2), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack. We can improve time complexity to O(n) by traversing the tree in a bottom-up manner where information is exchanged between the child nodes and parent node, which helps determine if the subtree rooted under any node is a BST in constant time.

We know that a binary tree is a BST if the following properties hold for every tree node:

  1. The left and right subtrees of every tree node are BST.
  2. A node’s value should be more than the largest value in the left subtree and less than the smallest value in the right subtree.

To determine if a subtree rooted under a node is a BST or not, the left subtree should provide information about the maximum value in it. The right subtree should provide information about the minimum value in it. Also, the parent node should be notified when both left and right child are also BST.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The size of the largest BST is 6

Java


Download  Run Code

Output:

The size of the largest BST is 6

Python


Download  Run Code

Output:

The size of the largest BST is 6