红黑树
(HashMap是用哈希表(直接一点可以说数组加单链表)+红黑树实现的map类)
查找方式:
链表(暴力)-》二叉树(无序)-》二叉查找树(和二分相似O(logn))-》特殊的二叉查找树(自平衡的二叉查找树)(红黑树)
如果构建的二叉查找树,不平衡,就会有最差的时间复杂度,为了避免不平衡:有了AVL(平衡二叉树)和红黑树
红黑树的性质:
变换:
1,变颜色
2,左旋
3,右旋
操作:
所有插入的点默认为红色
变颜色;
进行左旋
代码实现:
package RBTree;
//2021年4月7日上午10:54:47
//writer:apple
public class RBTree<K extends Comparable<K>,V> {
private static final boolean RED =true;
private static final boolean BLACK =false;
private RBNode root;
private RBNode parentoOf(RBNode node)//找父节点
{
if(node!=null) {
return node.parent;
}
return null;
}
private boolean isRed(RBNode node)//判断是否为红色
{
if(node!=null)
{
return node.color==RED;
}
return false;
}
private boolean isBlack(RBNode node)//判断是否为黑色
{
if(node!=null)
{
return node.color==BLACK;
}
return false;
}
private void setRed(RBNode node)//设置为红色
{
if(node!=null)
{
node.color=RED;
}
}
private void setBlack(RBNode node)//设置为黑色
{
if(node!=null)
{
node.color=BLACK;
}
}
//中序打印二叉树
public void inOrderPrint() {
inOrderPrint(this.root);
}
public void inOrderPrint(RBNode node)
{
if(node!=null)
{
inOrderPrint(node.left);
System.out.println(node.key+":"+node.value);
inOrderPrint(node.right);
}
}
//公开的插入方法
public void insert(K key,V value)
{
RBNode node=new RBNode();
node.setKey(key);
node.setValue(value);
node.setColor(RED);
insert(node);
}
//内部
private void insert(RBNode node)
{
RBNode parent=null;
RBNode x=this.root;
//先确定node的父结点
while(x!=null)
{
int cmp=node.key.compareTo(x.key);
if(cmp>0)
{
x=x.right;
}
else if(cmp==0)//就直接覆盖,因为不能出现相同的数
{
x.setValue(node.value);return;
}
else {
x=x.left;
}
}
node.parent=x;
if(parent!=null)
{
int cmp=node.key.compareTo(parent.key);
if(cmp>0)
{
parent.right=node;
}
else {
parent.left=node;
}
}
else {
//说明树为空
this.root=node;
}
//修复平衡树
insertFixUp(node);
}
//插入节点后,修复红黑树平衡的方法:
// 换颜色(情况1.1,自己为根节点换成黑色 情况1.2,父叔为红色(父叔改为黑色,爷结点改为红色)
// 左旋(情况2.1:父结点为红色,叔叔结点为黑色,自己(红色)为右子树。爷结点左旋
// 右旋(情况3.1:父结点为红色,叔叔结点为黑色,自己(红色)为左子树。父结点右旋
private void insertFixUp(RBNode node)
{
this.root.setColor(BLACK);//情况1.1,自己为根节点换成黑色
RBNode parent=parentoOf(node) ;
RBNode gparent=parentoOf(parent);
if<