333. Largest BST Subtree节点数最多的bst子树
2024-10-01 12:15:42
[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
最后结果可能是计算方法正确的负数,还没转过来,所以要再转一次。
[思维问题]:
如果每个点检查valid时都还要traverse,就会形成n2的复杂度。
return isValid(root.left, min, root.val) && isValid(root.right, root.val, max);
所以定义一个新的类,只管自己不管别人。
[英文数据结构或算法,为什么不用别的数据结构或算法]:
方法名和类名保持相同
[一句话思路]:
所以定义一个新的类,只管自己不管别人。因为算法没错,不对时直接*-1转过来就行。
Your input
[10,5,15,1,8,null,7]
Your stdout
left.res = 0
right.res = 1
root.val = 15
left.max = -2147483648
right.min = 7
Math.max(Math.abs(left.res), Math.abs(right.res)) = 1 left.res = 3
right.res = -1
root.val = 10
left.max = 8
right.min = 0
Math.max(Math.abs(left.res), Math.abs(right.res)) = 3 Your answer
3
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
定义一个新的类,只管自己不管别人。因为算法没错,不对时直接*-1转过来就行。
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class Result {
int res;
int min;
int max; public Result(int res, int min, int max) {
this.res = res;
this.min = min;
this.max = max;
}
} public int largestBSTSubtree(TreeNode root) {
Result result = helper(root);
return Math.abs(result.res);
} //divide and conquer, reverse or add to a new num
public Result helper(TreeNode root) {
//corner case
if (root == null) return new Result(0, Integer.MAX_VALUE, Integer.MIN_VALUE); //form left and right
Result left = helper(root.left);
Result right = helper(root.right); //reverse: root's val incorrect or res < 0
if (root.val < left.max || root.val > right.min || left.res < 0 || right.res < 0) {
return new Result(Math.max(Math.abs(left.res), Math.abs(right.res)) * (-1), 0, 0);
}else {
return new Result(1 + left.res + right.res, Math.min(left.min, root.val), Math.max(right.max, root.val));
}
}
}
最新文章
- 《转载》GET,POST,PUT,DELETE的区别
- CentOS SSH配置
- PHP中函数的使用
- PHP学习笔记 - 入门篇(3)
- Apache配置虚拟目录,以及各种操作
- 【创建型】Singleton模式
- OceanBase中主备Rootserver如何管理切换
- android在单身的对象和一些数据的问题被释放
- JavaWeb面试(六)
- 编程:在屏幕中间分别显示绿色、绿底红色、白底蓝色的字符串 &#39;welcome to masm!&#39;
- html_jQuery_ajax
- L347
- Codeforces 1118F1 Tree Cutting (Easy Version) (简单树形DP)
- python_day1 条件语句
- 实现Java Socket 客户端服务端交互实例
- Tronado
- list的遍历
- 字节顺序:高位优先(big-endian)和低位优先(little-endian)
- es倒排索引和正排索引
- 【性能测试工具ab】ab工具使用