LeetCode Largest BST Subtree
2016-02-13 04:50
253 查看
原题链接在这里:https://leetcode.com/problems/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.
Here's an example:
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Show Hint
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
采用bottom-up的方法,简历新的class, 用来存储
当前节点为root的subtree是否是BST
若是,最小val 和最大val.
size是当前subtree的大小。
然后从下到上更新,若是中间过程中size 比 res大,就更新res.
Time Complexity: O(n). 每个点不会访问超过两遍. Space: O(logn). Recursion stack space.
AC Java:
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 7
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree's size, which is 3.
Show Hint
Follow up:
Can you figure out ways to solve it with O(n) time complexity?
采用bottom-up的方法,简历新的class, 用来存储
当前节点为root的subtree是否是BST
若是,最小val 和最大val.
size是当前subtree的大小。
然后从下到上更新,若是中间过程中size 比 res大,就更新res.
Time Complexity: O(n). 每个点不会访问超过两遍. Space: O(logn). Recursion stack space.
AC Java:
/** * 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) { int [] res = {0}; helper(root, res); return res[0]; } private Node helper(TreeNode root, int [] res){ Node cur = new Node(); if(root == null){ cur.isBST = true; return cur; } Node left = helper(root.left, res); Node right = helper(root.right, res); if(left.isBST && root.val > left.max && right.isBST && root.val < right.min){ cur.isBST = true; cur.min = Math.min(root.val, left.min); cur.max = Math.max(root.val, right.max); cur.size = left.size + right.size + 1; if(cur.size > res[0]){ res[0] = cur.size; } } return cur; } } class Node{ boolean isBST; int min; int max; int size; public Node(){ isBST = false; min = Integer.MAX_VALUE; max = Integer.MIN_VALUE; size = 0; } }
相关文章推荐
- OpenSUSE Leap 42.1 改用国内源并更新系统
- A Calculator Supports Parentheses Written in C
- hdoj 3585 maximum shortest distance(二分+最大团)
- 关于drawRect:方法apple官方文档的翻译
- UIView的setNeedsLayout, layoutIfNeeded 和 layoutSubviews 方法之间的关系解释
- 深入分析LayoutInflater
- 递归例程的四条基本法则
- UIView的layoutSubviews和drawRect方法何时调用
- Docker —— 用于统一开发和部署的轻量级 Linux 容器【转】
- HUD 1874 畅通工程续(Dijkstra/spfa/floyd)
- 操作webbrowser页面输入框元素
- nginx源码分析—内存池结构ngx_pool_t及内存管理
- java 农历处理转换和显示输出
- select、poll和epoll的异同【整理】
- IOS不用AutoLayout也能实现自动布局的类(5)----MyFlowLayout横空出世
- nginx架构分析
- Kinect For Windows V2开发日志八:侦测、追踪人体骨架
- exit()那些事
- 在LINUX上创建GIT服务器【转】
- R语言-理解R性能