[Locked] Largest BST Subtree

时间:2023-03-09 16:54:15
[Locked] Largest BST Subtree

Largest BST Subtree

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.
Here's an example:

    10
/ \
5 15
/ \ \
1 8 7

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?

分析:

  典型树上的动态规划

代码:

//返回pair中4个值分别代表:是否是BST,BST的节点数,左边界,右边界
pair<pair<bool, int>, pair<int, int>> dfs(TreeNode *cur, int pval, int &maxl) {
pair<int, int> initp(pval, pval);
//为NULL,则返回真,两端值设为父节点的值便于下一步计算
if(!cur)
return make_pair(make_pair(true, ), initp);
//进行下一层遍历
pair<pair<bool, int>, pair<int, int>> leftp, rightp;
leftp = dfs(cur->left, cur->val, maxl);
rightp = dfs(cur->right, cur->val, maxl);
//判断是否为BST
if(leftp.first.first && rightp.first.first && cur->val >= leftp.second.second && cur->val <= rightp.second.first) {
int curlen = leftp.first.second + + rightp.first.second;
maxl = max(maxl, curlen);
return make_pair(make_pair(true, curlen), make_pair(leftp.second.first, rightp.second.second));
}
return make_pair(make_pair(false, ), initp);
}
int largestSubtree(TreeNode *root) {
int maxl = INT_MIN;
dfs(root, , maxl);
return maxl;
}