Trees: Is This a Binary Search Tree?

  • + 16 comments

    I think it's much simpler to just add the range check to the return condition. In that way you do not need to negate it and is explicit what it is doing.

    boolean checkBST(Node root) {
            return checkBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        boolean checkBST(Node node, int min, int max) {
            if (node == null) return true;
            return  min < node.data && node.data < max && 
                checkBST(node.left, min, node.data) && 
                checkBST(node.right, node.data, max);
        }