using System;
public
class Node {
public
int data;
public
Node left,
right;
public Node(int d) { data = d; }
}
public class GFG {
public static void Main(String[] args)
{
Node node1 = new Node(60);
node1.left = new Node(65);
node1.right = new Node(70);
node1.left.left = new Node(50);
Console.Write("Size of the largest BST is "
+ Solution.largestBst(node1) + "\n");
}
}
public
class Solution {
static int MAX = int.MaxValue;
static int MIN = int.MinValue;
public
class nodeInfo {
public int size;
public int max;
public int min;
public bool isBST;
public
nodeInfo()
{
}
public
nodeInfo(int size, int max, int min, bool isBST)
{
this.size = size;
this.max = max;
this.min = min;
this.isBST = isBST;
}
}
public
static nodeInfo
largestBST(Node root)
{
if (root == null) {
return new nodeInfo(0, MIN, MAX, true);
}
if (root.left == null && root.right == null) {
return new nodeInfo(1, root.data, root.data,
true);
}
nodeInfo left = largestBST(root.left);
nodeInfo right = largestBST(root.right);
nodeInfo returnInfo = new nodeInfo();
if (left.isBST && right.isBST
&& left.max < root.data
&& right.min > root.data) {
returnInfo.min = Math.Min(left.min, root.data);
returnInfo.max = Math.Max(right.max, root.data);
returnInfo.size = Math.Max(left.size, right.size) + 1;
returnInfo.isBST = true;
return returnInfo;
}
returnInfo.size = Math.Max(left.size, right.size);
returnInfo.isBST = false;
return returnInfo;
}
public
static int
largestBst(Node root)
{
return largestBST(root).size;
}
}