333. Largest BST Subtree
来源:互联网 发布:广联达软件安装 编辑:程序博客网 时间:2024/05/20 06:25
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int largestBSTSubtree(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } if (isValid(root, null, null)) { return countNode(root); } return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } private boolean isValid(TreeNode root, TreeNode min, TreeNode max) { if (root == null) { return true; } if (min != null && min.val >= root.val) { return false; } if (max != null && max.val <= root.val) { return false; } boolean valid = (isValid(root.left, min, root) && isValid(root.right, root, max)); return valid; } private int countNode(TreeNode root) { if (root == null) { return 0; } if (root.left == null && root.right == null) { return 1; } return 1 + countNode(root.left) + countNode(root.right); }}
阅读全文
0 0
- 333. Largest BST Subtree
- 333. Largest BST Subtree
- 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)
- [Leetcode] 333. Largest BST Subtree 解题报告
- Largest BST Subtree
- Largest BST Subtree
- LeetCode 333. Largest BST Subtree(最大二叉搜索树)
- Medium 333题 Largest BST Subtree
- Largest Subtree Which is a Binary Search Tree (BST)
- Subtree
- Subtree
- subTree
- 二叉树-Largest BST in a tree
- 闹钟实例与远程机制AIDL工具android:process=":remote"结合应用
- IOS基础控件 UISwitch swift3.1
- 2017年第0届浙江工业大学之江学院程序设计竞赛决赛 C: 勤劳的ACgirls
- 微信小程序开发mac上面卡死的解决办法
- 蓝桥-ALGO-19-方格取数
- 333. Largest BST Subtree
- Introduction to the Spring IoC container and beans
- python爬虫-模拟登陆新浪微+博爬取感兴趣人的所有信息
- POJ 1716 Integer Intervals(差分约束)
- iOS 可旋转的Chart 饼图
- 【python】redis基本命令和基本用法详解
- 注册表操作
- 淘淘商城系列——Redis的安装
- [FFT] [矩阵快速幂] [POJ3150] Cellular Automaton