int max =0;publicintlargestBSTSubtree(TreeNode root) {if (root ==null) {return max; }helper(root);return max; }privateResultTypehelper(TreeNode root) {if (root ==null) {// return size = 0, -infinity, +infinity - so that we can return the leaf value upreturnnewResultType(0,Integer.MAX_VALUE,Integer.MIN_VALUE); }ResultType left =helper(root.left);ResultType right =helper(root.right);// -1 means invalid BST, so we stop adding the nodes up if either subtree is not BST// if root's value is smaller than high of left || bigger than low of right// means it's not a BST, return -1 upif (left.size==-1||right.size==-1||root.val<=left.hight||root.val>=right.low) {returnnewResultType(-1,0,0);// doesn't matter what the bound is for non BST }// if we are here means, both left & right & current node is valid BST, add them upint curSize =left.size+right.size+1; max =Math.max(max, curSize); // update global max// return the size, and minreturnnewResultType(curSize,Math.min(left.low,root.val),Math.max(right.hight,root.val)); }}classResultType {int size; // size of this subtreeint low; // the lower bound that's validint hight; // the upper bound that's validpublicResultType(int s,int l,int h) { size = s; low = l; hight = h; }}