leetcode 98. Validate Binary Search Tree

按题意检查即可

可以递归,会比较好理解,逐渐收缩max和min

class Solution {
    public boolean isValidBST(TreeNode root) {
        return helper(root, Long.MAX_VALUE, Long.MIN_VALUE);
        
    }
    private boolean helper(TreeNode root , long max, long min){
        if(root == null)
            return true;
        if(root.val >= max || root.val <= min)
            return false;
        
        return helper(root.left, root.val, min) && helper(root.right, max, root.val);
    }
    

}

也可以迭代,利用中序遍历

class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if(root == null)
            return true;
        TreeNode pre = null;
        
        while(root != null || !stack.isEmpty()){
            while(root!= null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(pre != null && root.val <= pre.val)
                return false;
            pre = root;
            root = root.right;
        }
        return true;
        
    }
    

}

 

posted @ 2019-08-16 01:43  南山南北秋悲  阅读(143)  评论(0编辑  收藏  举报