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;
}

本文介绍了一种查找二叉树中最大二叉搜索树子树的方法,并提供了详细的递归算法实现。通过递归检查每个节点及其左右子树,确保子树符合二叉搜索树的定义。
674

被折叠的 条评论
为什么被折叠?



