Java集合与数据结构 Map和Set
搜索树
二叉搜索树又称二叉排序树,它或者是一棵空树**,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
- 它的左右子树也分别为二叉搜索树
操作:查找、插入、删除
逻辑代码:
class BinarySearchTree {
static class BSNode {
public int val;
public BSNode left;
public BSNode right;
public BSNode(int val) {
this.val = val;
}
}
public BSNode root = null;
/*
查找
*/
public BSNode search(int val) {
if(root == null) return null;
BSNode cur = root;
while (cur != null) {
if(cur.val == val) {
return cur;
}else if(cur.val < val) {
cur = cur.right;
}else {
cur = cur.left;
}
}
return null;
}
/*
插入
*/
public boolean insert(int val) {
BSNode bsNode = new BSNode(val);
if(root == null) {
root = bsNode;
return true;
}
BSNode cur = root;
BSNode parent = null;
while (cur != null) {
if(cur.val == val) {
return false;
}else if(cur.val < val) {
parent = cur;
cur = cur.right;
}else {
parent = cur;
cur = cur.left;
}
}
if(parent.val < val) {
parent.right = bsNode;
}else {
parent.left = bsNode;
}
return true;
}
/*
删除
*/
public void remove(int val) {
if (root == null) return;
BSNode cur = root;
BSNode parent = null;
while (cur != null) {
if (cur.val == val) {
removeNode(parent,cur,val);
return;
} else if (cur.val < val) {
parent = cur;
cur = cur.right;
} else {
parent = cur;
cur = cur.left;
}
}
}
public void removeNode(BSNode parent, BSNode cur, int val) {
if (cur.left == null) {
if (root == cur) {
root = cur.right;
} else if (parent.left == cur) {
parent.left = cur.right