![这里写图片描述](https://img-blog.csdn.net/20171114102723160?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvSGVhdERlYXRo/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![这里写图片描述](https://img-blog.csdn.net/20171114102729495?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvSGVhdERlYXRo/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
基础
public class BinarySearchTree<Key extends Comparable<Key>, Value> {
private class Node{
private Key key;
private Value value;
private Node left, right;
Node(Key key, Value value){
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
}
private Node root;
private int count;
public BinarySearchTree() {
root = null;
count = 0;
}
public int size() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
}
节点插入
public void insert(Key key, Value value) {
root = insert(root, key, value);
}
private Node insert(Node node, Key key, Value value) {
if (node == null) {
count++;
return new Node(key, value);
}
if (key.compareTo(node.key) == 0) {
node.value = value;
} else if (key.compareTo(node.key) > 0) {
node.right = insert(node.right, key, value);
} else {
node.left = insert(node.left, key, value);
}
return node;
}
查找
public boolean contain(Key key) {
return contain(root, key);
}
private boolean contain(Node node, Key key) {
if (node == null) {
return false;
}
if (key.compareTo(node.key) == 0) {
return true;
} else if (key.compareTo(node.key) > 0) {
return contain(node.right, key);
} else {
return contain(node.left, key);
}
}
public Value search(Key key) {
return search(root, key);
}
private Value search(Node node, Key key) {
if (node == null) {
return null;
}
if (key.compareTo(node.key) == 0) {
return node.value;
} else if (key.compareTo(node.key) > 0) {
return search(node.right, key);
} else {
return search(node.left, key);
}
}