Skip to content

Instantly share code, notes, and snippets.

@fizalihsan
Created May 16, 2016 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fizalihsan/73f5326f45b0f9f438496fc12634a1a0 to your computer and use it in GitHub Desktop.
Save fizalihsan/73f5326f45b0f9f438496fc12634a1a0 to your computer and use it in GitHub Desktop.
Checks if a given tree is a Binary Search Tree
public class BinarySearchTreeChecker {
public static void main(String[] args) {
Node<Integer> bsTree =
new Node<>(6,
new Node<>(4,
new Node<>(2, new Node<>(1), new Node<>(3)),
new Node<>(5)
),
new Node<>(9,
new Node<>(8, new Node<>(7), null),
new Node<>(10)
)
);
Node<Integer> nonBsTree =
new Node<>(6,
new Node<>(9,
new Node<>(2, new Node<>(1), new Node<>(3)),
new Node<>(5)
),
new Node<>(4,
new Node<>(8, new Node<>(7), null),
new Node<>(10)
)
);
System.out.println("Tree1 is BST? : " + checkBST(bsTree)); // true
System.out.println("Tree2 is BST? : " + checkBST(nonBsTree)); // false
System.out.println("Tree1 is BST, within 1 & 10? : " + checkBST(bsTree, 1, 10)); // true
System.out.println("Tree1 is BST, within 1 & 7? : " + checkBST(bsTree, 1, 7)); // false
System.out.println("Tree2 is BST, within 1 & 10? : " + checkBST(nonBsTree, 1, 10)); // false
}
/**
* Checks if the given tree is a BST + validates if the values are within the given legal range.
* low & high dictates what range of values are legal for the given node
*/
private static boolean checkBST(Node<Integer> root, int low, int high) {
if (root == null) return true; // Empty subtree
int rootkey = root.getValue();
if (rootkey < low || rootkey > high) {
return false; // Out of range
}
return checkBST(root.getLeft(), low, rootkey) && checkBST(root.getRight(), rootkey, high);
}
/**
* Just checks if the given tree is a BST
*/
private static boolean checkBST(Node<Integer> root) {
if (root == null) return true; // Empty subtree
int rootkey = root.getValue();
if (root.getLeft() != null && root.getLeft().getValue() > rootkey) { // check left child, if exists
return false;
}
if (root.getRight() != null && rootkey > root.getRight().getValue()) { // check right, if exists
return false;
}
return checkBST(root.getLeft()) && checkBST(root.getRight());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment