LeetCode 98: Validate Binary Search Tree

/**
 * 98. Validate Binary Search Tree
 * 1. Time:O(n)  Space:O(n)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(n)
class Solution {
    public boolean isValidBST(TreeNode root) {
        return helper(root,null,null);
    }

    private boolean helper(TreeNode root, Integer lower, Integer upper){
        if(root == null) return true;
        if(lower!=null && root.val<=lower) return false;
        if(upper!=null && root.val>=upper) return false;
        return helper(root.left,lower,root.val) && helper(root.right,root.val,upper);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root==null) return true;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while(!stack.isEmpty() || root!=null){
            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 @ 2020-05-07 11:56  AAAmsl  阅读(64)  评论(0编辑  收藏  举报