- 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.
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?
Difficulty:
Medium
解法1:后序遍历
这题要注意的是区分空节点和不符合BST性质的节点。
空节点也算BST树,要返回{INT_MAX, INT_MIN, 0}, 但不符合BST性质的节点就必须返回{}。
/*
Following is Binary Tree Node structure:
class TreeNode
{
public:
int data;
TreeNode *left, *right;
TreeNode() : data(0), left(NULL), right(NULL) {}
TreeNode(int x) : data(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : data(x), left(left), right(right) {}
};
*/
int maxCount = 0;
vector<int>

最低0.47元/天 解锁文章
348

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



