[leedcode 98] Validate Binary Search Tree
2015-07-16 22:17
253 查看
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.
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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { //[2147483647] //注意,因为root的val是int型的,其可能为最大值或最小值,因此一开始的设置最大或最小要使用long型,注意函数参数的类型 //本题非常巧妙使用最大值和最小值限制根节点的范围。最关键是对isvalid的正确定义,代表root的值是否在min和max中间 //本题另一个解法是:将二叉树中序遍历,然后检测是否是递增数组 return isvalid(root,(long)Integer.MIN_VALUE-1,(long)Integer.MAX_VALUE+1); } public boolean isvalid(TreeNode root,long min,long max){ if(root==null){ return true; } long val=(long)root.val; if(val>min&&val<max){ return isvalid(root.left,min,val)&&isvalid(root.right,val,max); }else return false; } }
相关文章推荐
- Delphi 实现微妙级别的延迟函数
- 程序设计项目实训——银行储蓄系统
- c#中和java中可变参数对比
- 归档—SharedPreferences(轻量级存储)
- 空瓶子换可乐
- 循环有序数组的查找
- Codeforces 577E Ann and Half-Palindrome 字典树
- C语言中的数组和字符串
- echarts数据专题图
- [C++ primer]C++四种强制类型转换
- 操作系统相关知识
- LeetCode---(69)Sqrt(x)
- C++慎用define,以及相关的替代的方法
- TOJ 3858 Home 搜索
- Jar ------META-INF的介绍
- 大数据将进入2.0时代(价值变现时代)
- string的不可变性
- 生成代码的代码 之 POJO生成器 之二 模板实现
- L3:equals()、String 类
- Project Euler:Problem 69 Totient maximum