Here is my code:
public boolean isBST() {
return isBST(this.root);
}
private boolean isBST(BinaryNode<T> rootNode) {
if (rootNode == null) {
return false;
}
if (rootNode.isLeaf()) {
return true;
}
T left = null;
T right = null;
if (rootNode.hasLeftChild()) {
left = rootNode.getLeftChild().getData();
if (left.compareTo(rootNode.getData()) < 0) {
return this.isBST(rootNode.getLeftChild());
}
else {
return false;
}
}
if (rootNode.hasRightChild()) {
right = rootNode.getRightChild().getData();
if (right.compareTo(rootNode.getData()) > 0) {
return this.isBST(rootNode.getRightChild());
}
else {
return false;
}
}
return true;
}
This code works for simple binary trees, but it doesn't work for other ones. Such as if I have a tree like so:
5
/ \
3 6
/\
1 2
It won't mark it false even thought it should since 2 is smaller than 3 and is in the wrong place. My code just checks the left child's left children, and the checks the right child's right children and not the inner children. What can I do to make this code work in the way that I wrote it? How can I modify it?