题目:
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.
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
思路:
一道bottom-up的深度优先搜索题目,也就是首先判断左右子树分别是不是合法的BST。如果是的话,我们还需要哪些信息呢?首先是需要知道左右子树的范围,因为我们要判断当前结点为根的树是否为二叉搜索树,就要满足当前结点大于左子树的最大值,并且小于右子树的最小值。其次我们还需要分别知道其左右子树上的最大合法BST的大小。有了这些信息,就可以判断以当前结点为根的二叉树是否为二叉搜索树了。
实现过程中有个小技巧,就是让DFS返回vector<int>。我原来传入了三个int的引用,写的代码又臭又长。。。
代码:
/**
* 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:
int largestBSTSubtree(TreeNode* root) {
int ans = 0;
DFS(root, ans);
return ans;
}
private:
vector<int> DFS(TreeNode *root, int &ans) {
if (!root) {
return vector<int>{0, INT_MAX, INT_MIN};
}
vector<int> left = DFS(root->left, ans);
vector<int> right = DFS(root->right, ans);
if (root->val > left[2] && root->val < right[1]) {
int min_value = min(root->val, left[1]);
int max_value = max(root->val, right[2]);
ans = max(ans, left[0] + right[0] + 1);
return vector<int>{left[0] + right[0] + 1, min_value, max_value};
}
return vector<int> {0, INT_MIN, INT_MAX};
}
};