public class BinaryTree<K extends Comparable, V extends Comparable> {
private Node root;
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public void insert(K key, V value) {
//如果根节点为空
if (this.root == null) {
this.root = new Node(key, value, null, null, null);
return;
}
Node temp = this.root;
int i = 0;
Node parent = null;
while (temp != null) {
parent = temp;
i = key.compareTo((K) this.root.key);
if (i > 0) {
temp = temp.right;
} else if (i == 0) {
temp.value = value;
} else {
temp = temp.left;
}
}
if (i > 0) {
parent.right = new Node(key, value, null, null, parent);
} else {
parent.left = new Node(key, value, null, null, parent);
}
}
public Node select(K key) {
if (this.root == null) {
return null;
}
Node temp = this.root;
while (temp != null) {
int i = key.compareTo(this.root.key);
if (i == 0) {
return temp;
} else if (i > 0) {
temp = temp.right;
} else {
temp = temp.left;
}
}
return null;
}
class Node<K, V> {
private K key;
private V value;
private Node right;
private Node left;
private Node parent;
public Node() {
}
public Node(K key, V value, Node right, Node left, Node parent) {
this.key = key;
this.value = value;
this.right = right;
this.left = left;
this.parent = parent;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
}