【本节目标】
1.了解实现搜索树
2.掌握 Map/Set 及实际实现类 HashMap/TreeMap/HashSet/TreeSet 的使用
3.掌握 HashMap 和 HashSet 背后的数据结构哈希表的原理和简单实现
1.搜索树
1.1 概念
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
- 它的左右子树也分别为二叉搜索树
1.2 操作-查找
1.3 操作-插入
1.
如果树为空树,即根
== null,直接插入

2.
如果树不是空树,按照查找逻辑确定插入位置,插入新结点
1.4
操作
-
删除(难点)
设待删除结点为
cur,
待删除结点的双亲结点为
parent
1. cur.left == null
1. cur 是 root ,则 root = cur.right2. cur 不是 root,cur 是 parent.left,则 parent.left = cur.right
3. cur 不是 root,cur 是 parent.right,则 parent.right = cur.right
2. cur.right == null
1. cur 是 root ,则 root = cur.left2. cur 不是 root , cur 是 parent.left ,则 parent.left = cur.left3. cur 不是 root , cur 是 parent.right ,则 parent.right = cur.left
3.
cur.left != null && cur.right != null
1. 需要使用替换法进行删除,即在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被 删除节点中,再来处理该结点的删除问题

1.4代码实现
public class BinarySearchTree {
static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public TreeNode root = null;
//查找
public TreeNode search(int key) {
TreeNode cur = root;
while (cur != null) {
if(cur.val < key) {
cur = cur.right;
}else if(cur.val > key) {
cur = cur.left;
}else {
return cur;
}
}
return null;
}
//插入
public void insert(int val) {
TreeNode node = new TreeNode(val);
if(root == null) {
root = node;
return;
}
TreeNode cur = root;
TreeNode parent = null;
while (cur != null) {
if(cur.val < val) {
parent = cur;
cur = cur.right;
}else if(cur.val > val) {
parent = cur;
cur = cur.left;
}else {
return;
}
}
//parent 指向的节点 就是 需要插入的节点位置 的 父亲节点
if(parent.val > val) {
parent.left = node;
}else {
parent.right = node;
}
}
//删除
public void remove(int key) {
TreeNode parent = null;
TreeNode cur = root;
while (cur != null) {
if(cur.val < key) {
parent = cur;
cur = cur.right;
}else if(cur.val > key) {
parent = cur ;
cur = cur.left;
}else {
removeNode(parent,cur);
return;
}
}
}
//删除
/**
* 三种情况
* @param parent
* @param cur
*/
private void removeNode(TreeNode parent,TreeNode cur) {
if(cur.left == null) {
if(cur == root) {
root = cur.right;
}else if(cur == parent.left) {
parent.left = cur.right;
}else {
parent.right = cur.right;
}
}else if(cur.right == null) {
if(cur == root) {
root = cur.left;
}if(cur == parent.left) {
parent.left = cur.left;
}else {
parent.right = cur.left;
}
}else {
//两边不为空的情况//右树的最小值为例子
TreeNode target = cur.right;
TreeNode targetP = cur;
while (target.left != null) {
targetP = target;
target = target.left;
}
cur.val = target.val;
if(target == targetP.left) {
targetP.left = target.right;
}else {
targetP.right = target.right;
}
}
}
}
2. Map 的使用
2.1 Map说明
Map
是一个接口类,该类没有继承自
Collection