相关概念
二叉树中每个节点都不能有多于两个的子节点。
二叉树的一个性质是一棵平均二叉树的深度要比节点个数N小得多。
二叉查找树, 其深度的平均值是O(logN)。
二叉查找树的实现
public class BinarySearchTree<T extends Comparable<? super T>> {
private static class BinaryNode<T>{
T element;
BinaryNode<T> left;
BinaryNode<T> right;
public BinaryNode(T element, BinaryNode<T> left, BinaryNode<T> right) {
this.element = element;
this.left = left;
this.right = right;
}
}
private BinaryNode<T> root;
public BinarySearchTree() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
public boolean contails(T x) {
return contails(x, root);
}
public void insert(T x) {
root = insert(x, root);
}
public T findMin() {
return findMin(root).element;
}
public T findMax() {
return findMax(root).element;
}
public void remove(T x) {
root = remove(x, root);
}
private boolean contails(T x,BinaryNode<T> t) {
//如果t是空集,直接return false
if (t == null) {
return false;
}
//与当前节点相比较,小于0说明x在当前左子树上,大于0说明x在当前右子树上,等于0说明当前节点就是x
int compareResult = x.compareTo(t.element);
if (compareResult < 0) {
return contails(x, t.left);
}else if (compareResult > 0) {
return contails(x, t.right);
}else {
return true;
}
}
private BinaryNode<T> insert(T x,BinaryNode<T> t) {
if (t == null) {
return new BinaryNode<T>(x, null, null);
}
int compareResult = x.compareTo(t.element);
if (compareResult < 0) {
t.left = insert(x, t.left);
}else if (compareResult > 0) {
t.right = insert(x, t.right);
}else {
}
return t;
}
private BinaryNode<T> findMin(BinaryNode<T> t) {
if (t == null) {
return null;
}else if (t.left == null) {
return t;
}
return findMin(t.left);
}
private BinaryNode<T> findMax(BinaryNode<T> t) {
if (t != null) {
while (t.right != null) {
t = t.right;
}
}
return t;
}
private BinaryNode<T> remove(T x,BinaryNode<T> t) {
if (t == null) {
return t;
}
//与当前节点相比较,小于0说明x在当前左子树上,大于0说明x在当前右子树上,等于0说明当前节点就是x
int compareResult = x.compareTo(t.element);
if (compareResult < 0) {
t.left = remove(x, t.left);
}else if (compareResult > 0) {
t.right = remove(x, t.right);
}else if (t.left != null && t.right != null) {
t.element = findMin(t.right).element;
t.right = remove(t.element, t.right);
}{
t= (t.left == null) ? t.right : t.left;
}
return t;
}
}