【LeetCode】Validate Binary Search Tree 二叉查找树的推断

题目: 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>


原文地址:https://www.cnblogs.com/wzzkaifa/p/6722622.html