Binary Search Tree
public class BST>{
@SuppressWarnings("ClassCanBeStatic")
private class BSTNode>{
BSTNode left, right;
U value;
public BSTNode(U value){
this.value = value;
}
// Adapted from Todd Davies answer to printing a BST on Stack Overflow.
// https://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram
private StringBuilder toString(StringBuilder prefix, boolean isTail, StringBuilder sb) {
if(right!=null) {
right.toString(new StringBuilder().append(prefix).append(isTail ? "│ " : " "), false, sb);
}
sb.append(prefix).append(isTail ? "└── " : "┌── ").append(value).append("\n");
if(left!=null) {
left.toString(new StringBuilder().append(prefix).append(isTail ? " " : "│ "), true, sb);
}
return sb;
}
@Override
public String toString() {
return this.toString(new StringBuilder(), true, new StringBuilder()).toString();
}
}
private BSTNode root;
private BSTNode search(BSTNode curr, E value){
if (curr == null || curr.value.equals(value)) return curr;
if (value.compareTo(curr.value) > 0)
return search(curr.right, value);
return search(curr.left, value);
}
public boolean contains(E value){
return search(root, value) != null;
}
private void printInOrder(BSTNode curr){
if (curr != null){
// Print left subtree
printInOrder(curr.left);
// Print curr
System.out.print(curr.value + " ");
// Print right subtree
printInOrder(curr.right);
}
}
public void printInOrder(){
printInOrder(root);
System.out.println();
}
/*
// Look-ahead version of insert.
private void insert(BSTNode curr, E value){
// In look-ahead, the only way curr can be null is if it's the root.
if (curr == null)
root = new BSTNode(value);
else if (value.compareTo(curr.value) > 0){
if (curr.right == null)
curr.right = new BSTNode(value);
else
insert(curr.right, value);
}
else if (value.compareTo(curr.value) < 0)
if (curr.left == null)
curr.left = new BSTNode(value);
else
insert(curr.left, value);
}
*/
private BSTNode insert(BSTNode curr, E value){
if (curr == null)
return new BSTNode(value);
if (value.compareTo(curr.value) > 0)
curr.right = insert(curr.right, value);
else if (value.compareTo(curr.value) < 0)
curr.left = insert(curr.left, value);
return curr;
}
public void insert(E value){
root = insert(root, value);
// For lookahead version:
//insert(root, value);
}
@Override
public String toString(){
return root.toString();
}
// Test code.
public static void main(String[] args){
BST bst = new BST<>();
bst.insert(8);
bst.insert(3);
bst.insert(1);
bst.insert(6);
bst.insert(4);
bst.insert(7);
bst.insert(10);
bst.insert(14);
bst.insert(13);
System.out.println(bst);
System.out.println("9? " + bst.contains(9));
System.out.println("7? " + bst.contains(7));
bst.printInOrder();
}
}