[LeetCode] 333. 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?
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.
这道题让我们求一棵二分树的最大二分搜索子树,所谓二分搜索树就是满足左<根<右的二分树,需要返回这个二分搜索子树的节点个数。题目中给的提示说可以用之前那道 Validate Binary Search Tree 的方法来做,时间复杂度为 O(n2),这种方法是把每个节点都当做根节点,来验证其是否是二叉搜索数,并记录节点的个数,若是二叉搜索树,就更新最终结果,参见代码如下:
解法一:
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
int res = ;
dfs(root, res);
return res;
}
void dfs(TreeNode *root, int &res) {
if (!root) return;
int d = countBFS(root, INT_MIN, INT_MAX);
if (d != -) {
res = max(res, d);
return;
}
dfs(root->left, res);
dfs(root->right, res);
}
int countBFS(TreeNode *root, int mn, int mx) {
if (!root) return ;
if (root->val <= mn || root->val >= mx) return -;
int left = countBFS(root->left, mn, root->val);
if (left == -) return -;
int right = countBFS(root->right, root->val, mx);
if (right == -) return -;
return left + right + ;
}
};
下面我们来看一种更简洁的写法,对于每一个节点,都来验证其是否是 BST,如果是的话,就统计节点的个数即可,参见代码如下:
解法二:
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
if (!root) return ;
if (isValid(root, INT_MIN, INT_MAX)) return count(root);
return max(largestBSTSubtree(root->left), largestBSTSubtree(root->right));
}
bool isValid(TreeNode* root, int mn, int mx) {
if (!root) return true;
if (root->val <= mn || root->val >= mx) return false;
return isValid(root->left, mn, root->val) && isValid(root->right, root->val, mx);
}
int count(TreeNode* root) {
if (!root) return ;
return count(root->left) + count(root->right) + ;
}
};
题目中的 Follow up 让用 O(n) 的时间复杂度来解决问题,还是采用 DFS 的思想来解题,由于时间复杂度的限制,只允许遍历一次整个二叉树,由于满足题目要求的二叉搜索子树必定是有叶节点的,所以思路就是先递归到最左子节点,然后逐层往上递归,对于每一个节点,都记录当前最大的 BST 的节点数,当做为左子树的最大值,和做为右子树的最小值,当每次遇到左子节点不存在或者当前节点值大于左子树的最大值,且右子树不存在或者当前节点值小于右子树的最小数时,说明 BST 的节点数又增加了一个,更新结果及其参数,如果当前节点不是 BST 的节点,那么更新 BST 的节点数 res 为左右子节点的各自的 BST 的节点数的较大值,参见代码如下:
解法三:
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
int res = , mn = INT_MIN, mx = INT_MAX;
isValidBST(root, mn, mx, res);
return res;
}
void isValidBST(TreeNode* root, int& mn, int& mx, int& res) {
if (!root) return;
int left_cnt = , right_cnt = , left_mn = INT_MIN;
int right_mn = INT_MIN, left_mx = INT_MAX, right_mx = INT_MAX;
isValidBST(root->left, left_mn, left_mx, left_cnt);
isValidBST(root->right, right_mn, right_mx, right_cnt);
if ((!root->left || root->val > left_mx) && (!root->right || root->val < right_mn)) {
res = left_cnt + right_cnt + ;
mn = root->left ? left_mn : root->val;
mx = root->right ? right_mx : root->val;
} else {
res = max(left_cnt, right_cnt);
}
}
};
上面的解法在递归函数中定义了大量的变量,难免让人看的眼花缭乱,我们可以稍稍精简一下,将这些变量都放到递归函数的返回值中,此时的helper函数返回了一个一维数组,里面有三个数字,分别是以当前结点为根结点的数的最小值,最大值,以及最大的 BST 子树的结点个数。那么就可以在边验证 BST 的过程中边统计个数,首先判空,若空,则返回一个默认三元组,整型最大值,最小值,和0。那你可能有疑问,定义的不是说第一个值是最小值么?没错,后面再解释。若当前结点 node 存在,分别对其左右子结点调用递归函数,那么左子树和右子树的信息都保存到了 left 和 right 数组中,就算左右子结点不存在也没关系,由于第一句的判空,还是会得到一个默认的三元组。接下来就是根据左右子树的信息来更新结果 res 了,由于 BST 的定义,当前结点值肯定是大于左子树的最大值,小于右子树的最小值的。左子树的最大值保存在 left[1] 中,右子树的最小值保存在 right[0] 中,如果这两个条件满足了,说明左右子树都是 BST,那么返回的三元组的最小值就是当前结点值和左子树最小值中的较小者,最大值就是当前结点值和右子树最大值中的较大值,返回的 BST 结点个数就是左右子树的结点个数加上1,即算上了当前结点。好,现在解释下为空时返回的三元组为何顺序是整型最大值,整型最小值。如果当前是叶结点,其也算是 BST,那么肯定希望能进入 if 从句,从而使得三元组的第三项能加1,但是 if 的条件是当前结点值要大于左子树中的最大值,现在左子结点是空的,为了保证条件能通过,我们将空的左子树的最大值设置为整型最小值,这样一定能通过,同理,将空的右子树的最小值设置为整型最大值,这就是空结点的三元组的作用。好,继续看 else 中的内容,如果破坏了 BST 的规则,则返回的三元组的最小值就是整型最小值,最大值是整型最大值,BST 结点个数并不是0,因为其左右子树中有可能还有 BST,所以是左右子树中的 BST 结点个数中的较大值,参见代码如下:
解法四:
class Solution {
public:
int largestBSTSubtree(TreeNode* root) {
vector<int> res = helper(root);
return res[];
}
vector<int> helper(TreeNode* node) {
if (!node) return {INT_MAX, INT_MIN, };
vector<int> left = helper(node->left), right = helper(node->right);
if (node->val > left[] && node->val < right[]) {
return {min(node->val, left[]), max(node->val, right[]), left[] + right[] + };
} else {
return {INT_MIN, INT_MAX, max(left[], right[])};
}
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/333
类似题目:
参考资料:
https://leetcode.com/problems/largest-bst-subtree/
https://leetcode.com/problems/largest-bst-subtree/discuss/78892/12ms-C%2B%2B-solution
https://leetcode.com/problems/largest-bst-subtree/discuss/78899/Very-Short-Simple-Java-O(N)-Solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 333. Largest BST Subtree 最大的二分搜索子树的更多相关文章
- [LeetCode] Largest BST Subtree 最大的二分搜索子树
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest mea ...
- LeetCode 333. Largest BST Subtree
原题链接在这里:https://leetcode.com/problems/largest-bst-subtree/ 题目: Given a binary tree, find the largest ...
- [leetcode]333. Largest BST Subtree最大二叉搜索树子树
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest mea ...
- 【LeetCode】333. Largest BST Subtree 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS 日期 题目地址:https://leetcod ...
- 333. Largest BST Subtree节点数最多的bst子树
[抄题]: Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where large ...
- 333. Largest BST Subtree
nlgn就不说了..说n的方法. 这个题做了好久. 一开始想到的是post-order traversal. 左右都是BST,然后自己也是BST,返还长度是左+右+自己(1). 左右其中一个不是,或者 ...
- Leetcode: Largest BST Subtree
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest mea ...
- [Swift]LeetCode333. 最大的二分搜索子树 $ Largest BST Subtree
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest mea ...
- Largest BST Subtree
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest mea ...
随机推荐
- Go命令行—compile
常用作编译命令行指定的单个go源码包.会生成一个以文件.o为后缀的目标文件,其文件名与包内第一个源文件的文件名相同. 目标文件可以与其他对象组合成一个包档案或直接传递给链接器(go tool link ...
- Oracle 11g 服务端的安装步骤
Ø 简介 本文主要介绍 Oracle 11g 服务端的安装步骤,在介绍之前说明以下几点: 1. 所安装的服务器是本机的虚拟机,操作系统为 Windows Server 2019: 2. 以下 ...
- javascript中的发布订阅模式与观察者模式
这里了解一下JavaScript中的发布订阅模式和观察者模式,观察者模式是24种基础设计模式之一. 设计模式的背景 设计模式并非是软件开发的专业术语,实际上设计模式最早诞生于建筑学. 设计模式的定义是 ...
- 【UOJ#308】【UNR#2】UOJ拯救计划
[UOJ#308][UNR#2]UOJ拯救计划 题面 UOJ 题解 如果模数很奇怪,我们可以插值一下,设\(f[i]\)表示用了\(i\)种颜色的方案数. 然而模\(6\)这个东西很有意思,\(6=2 ...
- .net core linux环境下 System.Data.SqlClient.SqlException: Connection Timeout Expired.
最近遇到了一个很奇葩的问题,我编写了一个.net core程序读取多个数据库数据源,进行数据同步处理.该程序在windows环境下运行完全正常,但在linux环境下运行报异常,提示 System.Da ...
- C# - VS2019 WinFrm程序调用ZXing.NET实现条码、二维码和带有Logo的二维码的识别
前言 C# WinFrm程序调用ZXing.NET实现条码.二维码和带有Logo的二维码的识别. ZXing.NET导入 GitHub开源库 ZXing.NET开源库githib下载地址:https: ...
- python3模块
一.sys模块 import sys #print(sys.path) #打印环境变量 #print(sys.argv) print(sys.argv[3]) Sys.argv[ ]其实就是一个列表, ...
- ubuntu玩坏之后
昨天,安装openssh-server的时候,与openssh-client冲突,故卸载openssh-client然后重装openssh-server解决问题. 今天,想装emacs,发现跟perl ...
- 通过MES技术居然可以防止制造数据造假?
近些年来我们经历了太多制造数据造假事件,特别是前段时间曝出的医药制造事件更是将我们群众的愤怒值推到了最高点.不过我们最应当做的是,冷静下来,思考一下各行各业的我们是不是都该做些什么了?毕竟当下一个灾难 ...
- rt-thread can
rt-thread stm32f10x-HAL can的驱动和应用.源码暂时还不支持,自己通过F4修改了一版 源码地址:https://gitee.com/gitee.thomas/rt_can rt ...