题目描述:
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Example:
Input: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
return maxNum(root)[0];
}
vector<int> maxNum(TreeNode* root)
{ // 返回的数组中有三个数,分别是当前节点中的最大BST节点数,当前所有节点的最大值,当前所有节点的最小值
// 当节点为空的时候,将最大值设为INT_MIN,最小值设为INT_MAX
// 这样是为了保证其他节点把它作为左节点时,left_max=INT_MIN
// 其他节点把它作为右节点时,right_min=INT_MAX,都可以组成BST
if(root==NULL) return {0,INT_MIN,INT_MAX};
vector<int> left=maxNum(root->left);
vector<int> right=maxNum(root->right);
int left_num=left[0], left_max=left[1], left_min=left[2];
int right_num=right[0], right_max=right[1], right_min=right[2];
if(root->left==NULL&&root->right==NULL) return {1,root->val,root->val};
else if(root->left!=NULL&&root->right==NULL&&root->val>left_max)
return {left_num+1,root->val,left_min};
else if(root->left==NULL&&root->right!=NULL&&root->val<right_min)
return {right_num+1,right_max,root->val};
else if(root->left!=NULL&&root->right!=NULL&&root->val<right_min&&root->val>left_max)
return {left_num+right_num+1,right_max,left_min};
// 当无法形成BST时,设置最大值为INT_MAX,最小值为INT_MIN,
// 如果其他节点把它作为左节点,left_max=INT_MAX,如果其他节点把它作为右节点,right_min=INT_MIN,
// 这样之后的任何节点都不可能和当前节点组成BST
else return {max(left_num,right_num),INT_MAX,INT_MIN};
}
};