structT{intmin;// Min value in the subtreeintmax;// Max value in the subtreeintsize;// Total size of the subtree};classSolution{public:intlargestBSTSubtree(TreeNode*root){returndfs(root).size;}private:Tdfs(TreeNode*root){if(root==nullptr)return{INT_MAX,INT_MIN,0};Tl=dfs(root->left);Tr=dfs(root->right);if(l.max<root->val&&root->val<r.min)return{min(l.min,root->val),max(r.max,root->val),1+l.size+r.size};// Mark as invalid one, but still record the size of children// Returns (-INF, INF) because any node won't > INT and < -INFreturn{INT_MIN,INT_MAX,max(l.size,r.size)};}};
classT{publicintmin;// Min value in the subtreepublicintmax;// Max value in the subtreepublicintsize;// Total size of the subtreepublicT(intmin,intmax,intsize){this.min=min;this.max=max;this.size=size;}}classSolution{publicintlargestBSTSubtree(TreeNoderoot){returndfs(root).size;}privateTdfs(TreeNoderoot){if(root==null)returnnewT(Integer.MAX_VALUE,Integer.MIN_VALUE,0);Tl=dfs(root.left);Tr=dfs(root.right);if(l.max<root.val&&root.val<r.min)returnnewT(Math.min(l.min,root.val),Math.max(r.max,root.val),1+l.size+r.size);// Mark as invalid one, but still record the size of children// Returns (-INF, INF) because any node won't > INT and < -INFreturnnewT(Integer.MIN_VALUE,Integer.MAX_VALUE,Math.max(l.size,r.size));}}