I’m not sure if this is an error by @Mosh or my understanding is flawed. In Mosh’s solution for validating binary search trees (lecture 16 of Binary Trees topic in The Ultimate Data Structures & Algorithms: Part 2) I see two issues. Code copied for clarity:
public boolean isBinarySearchTree() {
return isBinarySearchTree(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean isBinarySearchTree(Node root, int min, int max) {
if (root == null)
return true;
if (root.value < min || root.value > max)
return false;
return
isBinarySearchTree(root.leftChild, min, root.value - 1)
&& isBinarySearchTree(root.rightChild, root.value + 1, max);
}
First, if you store Integer.MAX_VALUE or Integer.MIN_VALUE in your tree it will fail the check implemented in isBinarySearchTree() even if it otherwise follows the rules for placement of the nodes. I know this is an obscure edge case, but writing a validation function that would reject a perfectly valid tree just seems off to me.
Second, in the recursion calls for the left and right children, he is adding (and subtracting) 1 from the passed min and max values. However, in the comparison operations he is using strictly less than (<) and strictly greater than (>). By doing this, it would reject adjacent numbers that would be perfectly acceptable node values. For example if your root.value
is 20 and its rightChild.value
is 21 (perfectly acceptable in a binary search tree) it will fail the next recursion step because he is saying isBinarySearchTree(root.rightChild, 21, Integer.MAX_VALUE)
when inspecting the right hand tree which fails when the next round checks 21 < 21
.
Maybe he got his thinking mixed up and was trying to address my first point, but forgot to change the comparison line to if (root.value <
= min || root.value >
= max)
. Then adding (or subtracting) 1 would make sense to allow the full range of Integer.MIN_VALUE
to Integer.MAX_VALUE
and prevent duplicate nodes.
As it stands now, this method does not properly validate binary search trees and flags perfectly acceptable structures as false.
Am I reading this wrong?