You are on page 1of 3

Largest BST

Problem Level: Hard

Problem Description:

Given a Binary tree, find the largest BST subtree. That is, you need to find the BST with maximum

height in the given binary tree. You have to return the height of the largest BST.

Sample Input 1:

5 10 6 2 3 -1 -1 -1 -1 -1 9 -1 -1

Sample Output 1:

Approach to be followed:

A Binary Tree is said to be a BST when the following two conditions are satisfied:

1. The value of the node should be greater than the maximum value of the left subtree and

lesser than the minimum of the right subtree.

2. The left and right subtree of every node are BST.

The key observation here is that if a subtree is a BST then all nodes in its subtree will also be a

BST. So, we will recurse on the binary tree in a bottom-up manner and use the information of the

left subtree and right subtree to store the information for the current subtree.

Steps:

1. Base case: If root is NULL, then return 0 as height of null tree is 0 and it is a BST.

2. For each node of the tree, store the following:

a. ‘isBST’, denoting whether it is a BST

b. ‘height’, denoting the height of the subtree

c. ‘min’, denoting the minimum value of data in the left subtree

d. ‘max’, denoting the maximum value of data in the right subtree


3. Recursively call on the left and right subtree to find the height of the subtree which is

BST.

4. For the currentnode, check if the left subtree is BST or the right subtree is BST. Also

check if the value of the root node is greater than the maximum of left subtree value and

lesser than the minimum of right subtree values.

5. If the aforementioned conditions satisfy, find the maximum of left height and right height

of the currnode and return it.

Pseudo Code:
class bstSubtreeReturn:

max = 0

min = 0

height = 0

isBST = False

function largestBSTSubtree(root):

return Helper(root).height

function helper(root):

if root is null :

ans = bstSubtreeReturn()

ans.max = INT_MIN

ans.min = INT_MAX

ans.isBST = True

ans.height = 0

return ans

left = Helper(root.left)

right = Helper(root.right)

if not (right.isBST and right.min is greater than root.data):

right.isBST = false
if not (left.isBST and left.max is less than root.data):

left.isBST = false

ans = bstSubtreeReturn()

if not (left.isBST or not right.isBST or root.data less than


left.max or root.data greater than right.min):

if left.height greater than right.height:

left.isBST = false

return left

else:

right.isBST = false

return right

ans.isBST = True

ans.min = min(left.min,min(right.min,root.data))

ans.max = max(left.max,max(right.max,root.data))

ans.height = max(left.height, right.height) + 1

return ans

Time Complexity: O(N), where N denotes the number of nodes in the binary tree.
Since every node of the binary tree will be visited at most once, the time complexity will be O(N).

You might also like