/// <summary> /// returns the largest BST in a BT /// </summary> /// <param name="root"></param> /// <returns></returns> private static MinMaX LargestBSTree(Tree root) { if (root == null) { return(new MinMaX()); } MinMaX leftMinMax = LargestBSTree(root.Left); MinMaX rightMinMax = LargestBSTree(root.Right); MinMaX current = new MinMaX(); if (leftMinMax.IsBST == false || rightMinMax.IsBST == false || (leftMinMax.Max > root.Data) || (rightMinMax.Min < root.Data)) { current.IsBST = false; current.Size = Math.Max(leftMinMax.Size, rightMinMax.Size); return(current); } current.IsBST = true; current.Size = leftMinMax.Size + rightMinMax.Size + 1; current.Min = root.Left != null ? leftMinMax.Min : root.Data; current.Max = root.Right != null ? rightMinMax.Max : root.Data; return(current); }
public static int LargestBST(Tree root) { MinMaX m = LargestBSTree(root); return(m.Size); }