[Leetcode] 333. Largest BST Subtree 解题报告
来源:互联网 发布:2017淘宝开店认证手机 编辑:程序博客网 时间:2024/05/20 07:50
题目:
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}; }};
阅读全文
0 0
- [leetcode] 333. Largest BST Subtree 解题报告
- [Leetcode] 333. Largest BST Subtree 解题报告
- LeetCode 333. Largest BST Subtree
- LeetCode 333. Largest BST Subtree
- leetcode 333. Largest BST Subtree
- Leetcode 333. Largest BST Subtree (Medium) (cpp)
- 333. Largest BST Subtree
- 333. Largest BST Subtree
- 333. Largest BST Subtree
- LeetCode 333. Largest BST Subtree(最大二叉搜索树)
- Largest BST Subtree
- Largest BST Subtree
- 【LeetCode】Subtree of Another Tree 解题报告
- 【LeetCode】Largest Number 解题报告
- 【LeetCode】Largest Number 解题报告
- 【LeetCode】Largest Number 解题报告
- [LeetCode]Largest Number, 解题报告
- LeetCode-Largest Number-解题报告
- jQuery 将本地时间转换成 UTC 时间,计算时差,将UTC时间转换成 本地 时间
- MySQL学习随记---存储函数
- C语言 搜索字符串中的逗号有感(关于数据中的ASCII码)
- Android 复制和粘贴功能
- hdu5690(快速幂||减半)All X
- [Leetcode] 333. Largest BST Subtree 解题报告
- ORA-12518
- 【已解决】C#获取CPU温度支持Win10(OpenHardwareMonitor)
- 屏幕分辨率
- 欢迎使用CSDN-markdown编辑器
- build opencv cmake-gui 配置eigen路径
- 题目十九 汽车考察
- 大数定律1
- Eclipse常用快捷键