-
-
Save fizalihsan/73f5326f45b0f9f438496fc12634a1a0 to your computer and use it in GitHub Desktop.
Checks if a given tree is a Binary Search Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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