Skip to content

Instantly share code, notes, and snippets.

@chrislukkk
Created July 8, 2014 02:42
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 chrislukkk/24270f55880fa1060d53 to your computer and use it in GitHub Desktop.
Save chrislukkk/24270f55880fa1060d53 to your computer and use it in GitHub Desktop.
CareerCup_4.5 - Check if binary tree is BST
package Chapter4;
import java.util.Stack;
public class BSTChecker {
public static <T extends Comparable<T>> boolean isBST(BinaryTree<T> tree) {
Stack<TreeNode<T>> stack = new Stack<>();
TreeNode<T> cur = tree.root();
T prevKey = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
if (!stack.isEmpty()) {
cur = stack.pop();
if (prevKey != null && cur.key.compareTo(prevKey) < 0) {
return false;
}
prevKey = cur.key;
cur = cur.right;
}
}
return true;
}
public static void main(String[] args) {
/* _______7______
/ \
__10__ ___2
/ \ /
4 3 _8
\ /
1 11 */
Integer[] pre = { 7, 10, 4, 3, 1, 2, 8, 11 };
Integer[] in = { 4, 10, 3, 1, 7, 11, 8, 2 };
BinaryTree<Integer> bt1 = BinaryTreeBuilder.buildTree(pre, in);
System.out.println("tree A is BST: " + isBST(bt1));
/* _______7______
/ \
__2__ __11
/ \ /
1 3 10
\ /
4 8 */
Integer[] pre2 = { 7, 2, 1, 3, 4, 11, 10, 8 };
Integer[] in2 = { 1, 2, 3, 4, 7, 8, 10, 11 };
BinaryTree<Integer> bt2 = BinaryTreeBuilder.buildTree(pre2, in2);
System.out.println("tree B is BST: " + isBST(bt2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment