// Given a binary tree, find the largest Binary Search Tree (BST), // where largest means BST with largest number of nodes in it. // The largest BST must include all of its descendants. public LargestBST largestBSTSubtree2(Node node) { if (node == null) { return(null); } if (node.Left == null && node.Right == null) { return(new LargestBST(node, node.GetHashCode(), node.Data, node.Data)); } LargestBST LeftNode = largestBSTSubtree2(node.Left); LargestBST RightNode = largestBSTSubtree2(node.Right); if (LeftNode != null && RightNode != null) { if ((node.Data > LeftNode.max && node.Left == LeftNode.node) && (node.Data < RightNode.min && node.Right == RightNode.node)) { LargestBST bst = new LargestBST(node, LeftNode.maxNode + RightNode.maxNode + 1, LeftNode.min, RightNode.max); return(bst); } else { return((LeftNode.maxNode > RightNode.maxNode) ? LeftNode : RightNode); } } else if (LeftNode != null) { if (node.Data > LeftNode.max && node.Left == LeftNode.node) { return(new LargestBST(node, LeftNode.maxNode + 1, LeftNode.min, node.Data)); } else { return(LeftNode); } } else if (RightNode != null) { if (node.Data < RightNode.min && node.Right == RightNode.node) { return(new LargestBST(node, RightNode.maxNode + 1, node.Data, RightNode.max)); } else { return(RightNode); } } return(null); }