[LeetCode] 98. 验证二叉搜索树

方法一:

long pre=Long.MIN_VALUE;
    public boolean isValidBST3(TreeNode root){
        if(root==null) return true;
        if(!isValidBST3(root.left)) return false;
        if(root.val<=pre)return false;
        pre=root.val;
        return isValidBST3(root.right);
    }

 

 方法二:

/**
 * 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) {
        Stack<TreeNode> stack=new Stack<>();
        double inorder=-Double.MAX_VALUE;

        while(!stack.isEmpty()||root!=null){
            while (root!=null){
                stack.push(root);
                root=root.left;
            }
            root=stack.pop();
            if(root.val<=inorder){
                return false;
            }
            inorder=root.val;
            root=root.right;
        }
        return true;
    }
}

 

 方法三:

/**
 * 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) {
        return helper(root,null,null);
    }

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

 

posted @ 2020-05-06 00:40  doyi  阅读(205)  评论(0编辑  收藏  举报