Simple 0ms java solution with dfs


  • 0
    C
    public boolean isValidBST(TreeNode root) {
            return dfs(root, (long)(Integer.MIN_VALUE)-1, (long)(Integer.MAX_VALUE)+1);
        }
        private boolean dfs(TreeNode root, long gt, long lt){
            if(root == null) return true;
            if(root.val >= lt || root.val <= gt) return false;
            return dfs(root.left, gt, root.val) && dfs(root.right, root.val, lt);
        }
    

    Note: I found that my solution is similar to another thread however I came up with this answer all by myself.


  • 0
    P

    Thanks for sharing! May I ask you why we have to convert Interger.MIN_VALUE /MAX_VALUE to type long otherwise it won't pass the [2,1,3] sort of test? Thx!


  • 0
    C

    @phatfathu
    because if you don't do that, due to bits limit, Integer.MIN_VALUE-1 and Integer.MAX_VALUE +1 will not be what they are intended to be. They will go back to 0(not sure)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.