给定一个二叉树,找到其中最大的二叉搜索树(BST)子树,其中最大指的是子树节点数最多的。
输入: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
其中最大的BTS子树是 5 1 8
1.判断是不是BTS:
1 | bool bst(TreeNode* root) { |
2.统计某个树的结点数量:1
2
3
4
5
6int num(TreeNode* root) {
if (root == NULL) return 0;
int left = num(root->left);
int right = num(root->right);
return left + right + 1;
}
3.实现:1
2
3
4
5
6
7
8
9
10
11
12int largestBSTSubtree(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (bst(root)) {
return num(root);
}
int left = largestBSTSubtree(root->left);
int right = largestBSTSubtree(root->right);
return max(left, right);
}