题目链接: https://leetcode.com/problems/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 7The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Hint:
- You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
思路: 按照正常的top-down的思路就是依次判断当前结点为根的树是否为搜索二叉树, 这个并不难, 只要在向左右搜索的时候带一个范围即可. 这种方法的时间复杂度是O(n!), 因此对于很大的树将极为耗时. 但是如果用bottom-up的话将可将时间复杂度降为O(n), 这是一个极大的优化.
现在来考虑一下bottom-up我们需要从子树获得哪些信息? 首先肯定是需要子树的范围, 因为我们要判断当前结点为根的树是否为二叉搜索树就要满足当前结点大于左子树的最大值, 小于右子树的最小值. 再次我们还需要知道子树是否为二叉搜索树以及其二叉搜索树的大小. 有了这些信息我们就可以判断以当前结点为根的二叉树是否为二叉搜索树了. 但是这题很容易写的比较复杂.
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> DFS(TreeNode* root, int& ans)
{
if(!root) return vector<int>{0, INT_MAX, INT_MIN};
auto left=DFS(root->left, ans), right=DFS(root->right, ans);
if(root->val > left[2] && root->val < right[1])
{
int Min =min(root->val, left[1]), Max =max(root->val, right[2]);
ans = max(ans, left[0] + right[0] + 1);
return vector<int>{left[0] +right[0] +1, Min , Max};
}
return vector<int>{0, INT_MIN, INT_MAX};
}
int largestBSTSubtree(TreeNode* root) {
int ans = 0;
DFS(root, ans);
return ans;
}
};