树:红黑树,线段树。手撕源码。从入门到入坑 更新版

红黑树

(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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值