跟个nt一样,没看懂题;
题目要求的事满足二叉树子树的最大节点个数;
而不是左右子树;
这个题值得二刷,代码思路和写法很有建设性;
具体代码:
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
if(!root)
return 0;
if(vaild(root, INT_MIN, INT_MAX))
return cnt(root);
return max(largestBSTSubtree(root->left),largestBSTSubtree(root->right));
}
int cnt(TreeNode* root){
if(!root)
return 0;
return cnt(root->left)+cnt(root->right)+1;
}
bool vaild(TreeNode* root,int l,int r){
if(!root)
return true;
if(root->val<=l||root->val>=r)
return false;
return vaild(root->left,l,root->val)&&vaild(root->right,root->val,r);
}
};



