Share my clean AC java code

  • 0

    Use max and min to check every node, return false if one not in the range. use long to dealwith MAX_VALUE and MIN_VALUE.

    public boolean isValidBST(TreeNode root) {
        return checkNode(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    protected boolean checkNode(TreeNode node, long min, long max){
        if(node == null) return true;
        if(!(node.val <= max && node.val >= min)) return false;
        return checkNode(node.left, min, (long)(node.val)-1) && checkNode(node.right, (long)(node.val)+1, max);

    Hope it helps.

Log in to reply

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