您的位置:首页 > 其它

LeetCode 333. Largest BST Subtree

2016-05-26 01:59 429 查看
I am absolutely not good at bottom-up traversal.

/*
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.
*/

int largestBSTSubtree(TreeNode* root) {
int mmin;
int mmax;
int nodes = 0;
helper(root, mmin, mmax, nodes);
return nodes;
}

bool helper(TreeNode* root, int& mmin, int& mmax, int nodes) {
if(!root) return true;
int lMin = INT_MAX;
int lMax = INT_MIN;
int lNode = 0;
auto lValid = helper(root->left, lMin, lMax, lNode);
int rMin = INT_MAX;
int lMax = INT_MIN;
int rNode = 0;
auto rValid = helper(root->right, rMin, rMax, rNode);
if(lValid == false || rValid == false || root->val <= lMin || root->val >= rMax) {
nodes = max(lNode, rNode);
return false;
}
mmin = min(lMin, root->val);
mmax = max(rMax, root->val);
nodes = lNode + rNode + 1;
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: