Professional Documents
Culture Documents
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
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.
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
5. If the aforementioned conditions satisfy, find the maximum of left height and right height
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)
right.isBST = false
if not (left.isBST and left.max is less than root.data):
left.isBST = false
ans = bstSubtreeReturn()
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))
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).