Given a binary tree, I want to find out the largest subtree which is a BST in it.
Naive approach:
I have a naive approach in mind where I visit every node of
To verify if a node is root of a BST , we have to recursively check each left and right children . If you start from root , you will have to recur all children before you can decide root of the binary tree is a BST or not . So it do not make any sense to call "isBST" for each node . Here's my approach
Couple of challenges in making this work is storing max so far for which i used a ref variable MaxNumNodes. maxbst withh have the root of the biggest BST found when the function return .
public int MaxBST(Node root, int min, int max, ref Node maxbst,
ref int MaxNumNodes)
{
if (root == null) return 0;
//Not a BST
if (root.data < min || root.data > max) return -1;
//Find Max BST on left
int left = MaxBST(root.left, min, root.data, ref maxbst,
ref MaxNumNodes);
//Find Max BST on right
int right = MaxBST(root.right, root.data + 1, max, ref maxbst,
ref MaxNumNodes);
//Case1: -1 from both branches . No BST in both branches
if (left == -1 && right == -1) return -1;
//Case2:No BST in left branch , so choose right
//See if the BST on right is bigger than seen so far
if (left == -1)
{
if (right> MaxNumNodes)
{
MaxNumNodes = right;
maxbst = root.right;
}
return -1;
}
//Case3:No BST in right branch , so choose left
//See if the BST on left is bigger than seen so far
if (right == -1)
{
if (left > MaxNumNodes)
{
MaxNumNodes = left;
maxbst = root.left;
}
return -1;
}
//Case4:Both are BST , new max is left BST + right BST
maxbst = root;
return left + right + 1;
}