To find the largest BST subtree, there are two cases:

- the given tree itself is a BST, then return its total number of nodes.
- otherwise, the largest BST subtree is in its left or/and right substree(s).

For case 1, use recursion to check if both subtrees are also BST and also in required value range.

For case 2, use recursion to find largest BST subtree by design.

```
int largestBSTSubtree(TreeNode* r) {
int numNode;
if (isBST(r, INT_MIN, INT_MAX, numNode)) return numNode;
return std::max(largestBSTSubtree(r->left), largestBSTSubtree(r->right));
}
// helper function to check if a binary tree is BST and also calculates number of nodes if true
bool isBST(TreeNode* r, int min, int max, int& numNode) {
if (!r) {
numNode = 0;
return true;
}
if (r->val < min || r->val > max) return false;
int leftNode, rightNode;
bool leftValid = isBST(r->left, min, r->val, leftNode);
if (!leftValid) return false;
bool rightValid = isBST(r->right, r->val, max, rightNode);
if (rightValid) {
numNode = 1 + leftNode + rightNode;
return true;
}
else return false;
}
```