二叉搜索树的查找
-原理
public static Integer get(int key){
BinarySearchNode cur = root;
while(cur != null){
if(key < cur.key){
cur = cur.left;
}
else if(key > cur.key){
cur = cur.right;
}else {
return cur.val;
}
}
return null;
}
二叉搜索树的插入
-原理
public static void put(int key, int val){
if(root == null){
root = new BinarySearchNode(key, val);
return;
}
BinarySearchNode parent = null;
BinarySearchNode cur = root;
while(cur != null){
if(key < cur.key){
parent = cur;
cur = cur.left;
}
else if(key >cur.key){
parent = cur;
cur = cur.right;
}else{
cur.val = val;
return;
}
}
BinarySearchNode newNode = new BinarySearchNode(key, val);
if(newNode.key < parent.key){
parent.left = newNode;
}else{
parent.right = newNode;
}
return;
}
二叉搜索树的删除
-原理
public static void remove(int key){
BinarySearchNode cur = root;
BinarySearchNode parent = null;
while(cur != null){
if(key < cur.key){
parent = cur;
cur = cur.left;
}
else if(key > cur.key){
parent = cur;
cur = cur.right;
}else{
removeNode(parent, cur);
return;
}
}
}
private static void removeNode(BinarySearchNode parent, BinarySearchNode cur) {
if(cur.left == null){
if(cur == root){
root = cur.right;
}
else if(cur == parent.right){
parent.right = cur.right;
}else if(cur == parent.left){
parent.left = cur.right;
}
}
else if(cur.right == null){
if(cur == root){
root = cur.left;
}
else if(cur == parent.right){
parent.right = cur.left;
}else if(cur == parent.left){
parent.left = cur.left;
}
}else{
BinarySearchNode goat = cur.right;
BinarySearchNode goatparent = cur;
while(goat.left != null){
goatparent = goat;
goat = goat.left;
}
cur.key = goat.key;
cur.val = goat.val;
if(goat == goatparent.right){
goatparent.right = goat.right;
}else{
goatparent.left = goat.right;
}
}
}