Validate Binary Search Tree
2016-07-08 10:29
281 查看
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
A single node tree is a BST
Example
An example:
The above binary tree is serialized as
分析:
解题思路可以根据bst的特性来,对于每个子树,我们给他们一个最小和最大的范围。
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
A single node tree is a BST
Example
An example:
2 / \ 1 4 / \ 3 5
The above binary tree is serialized as
{2,1,4,#,#,3,5}(in level order).
分析:
解题思路可以根据bst的特性来,对于每个子树,我们给他们一个最小和最大的范围。
public class Solution { public boolean isValidBST(TreeNode root) { return vilidateChild(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean vilidateChild(TreeNode node, long min, long max) { if (node == null) return true; if (node.val < max && node.val > min) { return vilidateChild(node.left, min, node.val) && vilidateChild(node.right, node.val, max); } else { return false; } } }
相关文章推荐
- 7. Reverse Integer
- limit MySql
- ue4攻击目标的具体骨骼
- 电脑睡眠状态
- opencv自带SVM非线性分类的小问题
- useR! talk on teaching R
- Hibenate的JDBC的使用
- 排序算法之——冒泡排序
- 周志华 机器学习 学习笔记 (1)
- domain的一些理解
- 24年的第一天
- [mtk]按power键亮屏速度慢问题
- fatal error RC1015: cannot open include file ‘afxres.h’ 的一种解决方法
- PullToRefreshListView addHeadView的正确姿势
- STM32 ——端口复用和重映射
- hibernate执行hql查询出现java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I之解法
- unity调取windows保存或读取窗口
- volatile关键字简介
- udp传输文件
- DockerFile实战(二):DockerFile编写要求与基本风格