二叉查找树
1. 定义
- 若左子树不空,则左子树上所有结点的值均小于它的根结点的值
- 若右子树不空,则右子树上所有结点的值均大于它的根结点的值
- 左、右子树也分别为二叉查找树
- 没有键值相等的结点
2. 增删查
2.1 插入
public void insert(T val) {
if (val == null)
throw new NullPointerException();
root = insert(val, root);
}
/**
* 插入方法的实际执行
*/
private Node<T> insert(T val, Node<T> t) {
if (root == null) {
return new Node<>(val, null, null);
}
int compareRes = val.compareTo(root.value);
if (compareRes > 0) {
root.right = insert(val, root.right);
} else if (compareRes < 0) {
root.left = insert(val, root.left);
}
return t;
}
2.2 查找
查找树中是否包含此值
/**
* 查看二叉树中是否包含此值
*/
public boolean contains(T val) {
if (val == null) {
throw new NullPointerException();
}
return contains(val, root);
}
private boolean contains(T val, Node<T> t) {
if (t == null) {
return false;
}
int compareRes = val.compareTo(t.value);
if (compareRes > 0) {
return contains(val, t.right);
} else if (compareRes < 0) {
return contains(val, t.left);
} else {
return true;
}
}
2.3 查找最大值
/**
* 获取最大值
*/
public T findMax() {
if (root == null) {
return null;
}
return findMax(root).value;
}
private Node<T> findMax(Node<T> t) {
while (t.right != null)
t = t.right;
return t;
2.4 查找最小值
/**
* 获取最小值
*/
public T findMin() {
if (root == null) {
return null;
}
return findMin(root).value;
}
private Node<T> findMin(Node<T> t) {
while (t.left != null) {
t = t.left;
}
return t;
}
2.5 删除
public Node<T> delete(T val) {
if (val == null)
throw new NullPointerException();
return delete(val, root);
}
private Node<T> delete(T val, Node<T> t) {
if (t == null)
return null;
int compareRes = val.compareTo(t.value);
if (compareRes > 0)
delete(val, t.right);
else if (compareRes < 0)
delete(val, t.left);
else if (t.left != null && t.right != null) {
Node<T> temp = findMin(t.right);
t.value = temp.value;
delete(val,temp);
}else
t = (t.left ==null ? t.right:t.left);
return t;
}