题目: Given a binary tree, determine if it is a valid binary search tree (BST).
知识点:BST的特点:
1、一个节点的左子树的所有点都小于或等于这个点的值,右子树的所有节点的值大于该节点的值;
2、最左节点值最小,最右节点值最大;
3、中序遍历结果值是一个非降的数列
问题:如果用Integer.MAX_VALUE会过不了测试用例,可是按照TreeNode中的定义,val值也是int呀,没办法用了Long,如果谁知道,麻烦解释一下哦。。
<span style="font-size:18px;">/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root){
return helper2( root, Long.MAX_VALUE, Long.MIN_VALUE);
}
private boolean helper2(TreeNode root, long maxValue, long minValue) {
if(root == null) return true;
if(root.val >= maxValue || root.val <= minValue) return false;
return helper2(root.left, root.val, minValue) && helper2(root.right, maxValue, root.val);
}
}</span>【LeetCode】Validate Binary Search Tree 二叉查找树的判断
原文地址:http://blog.csdn.net/ymzmdx/article/details/44314033