333. 最大 BST 子树
思路:这题用递归,如果root是bst树,就返回其节点值,返回时与最大的节点值进行比较,更新最大值,若不是,直接返回-1,需要注意的就是怎么判断这个树是不是bst树,需要那root的值和左子树的最小值以及右子树的最大值进行比较!
class Solution {
private int maxCount=0;
public int largestBSTSubtree(TreeNode root) {
count(root);
return maxCount;
}
public int count(TreeNode root){
if(root==null) return 0;
if(root.right==null&&root.left==null){
maxCount=Math.max(maxCount,1);
return 1;
}
int left=count(root.left);
int right=count(root.right);
if(left==-1||right==-1)return -1;
if(root.left==null&&findMin(root.right)>root.val){
maxCount=Math.max(maxCount,left+right+1);
return left+right+1;
}else if(root.right==null&&findMax(root.left)<root.val){
maxCount=Math.max(maxCount,left+right+1);
return left+right+1;
}else{
if(root.right!=null&&root.left!=null
&&findMin(root.right)>root.val&&findMax(root.left)<root.val){
maxCount=Math.max(maxCount,left+right+1);
return left+right+1;
}
return -1;
}
}
public int findMax(TreeNode root){
while(root.right!=null){
root=root.right;
}
return root.val;
}
public int findMin(TreeNode root){
while(root.left!=null){
root=root.left;
}
return root.val;
}
}