Binary search tree
1. Definitions
- If the left subtree is not empty, then the value of the left sub-tree, all the nodes are less than the value of its root
- If the right subtree is not empty, then the right sub-tree nodes are all values greater than the value of its root
- Left and right subtrees are also binary search tree
- It does not equal node key
2. deletions check
2.1 Inserting
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;
}
Find 2.2
Find the tree contains this value
/**
* 查看二叉树中是否包含此值
*/
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;
}
}
Find the maximum value of 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;
Find the minimum value of 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 Delete
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;
}