四刷98. Validate Binary Search Tre

2018-02-01  本文已影响0人  greatseniorsde

还是没做出来,这道题的方法是比较特别,记住吧。为什么要初始化为null,是因为不知道上下限。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null){
            return true;
        }
        return helper(root, null, null);
    }
    
    private boolean helper(TreeNode root, Integer min, Integer max){
        if (root == null){
            return true;
        }        
        if (min != null && root.val <= min || (max != null && root.val >= max)){
            return false;
        }
        return helper(root.left, min, root.val) && helper(root.right, root.val, max);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读