一直很想写一个关于树结构的专题,再一个就是很多初级点的码农会认为树结构无用论,其实归根到底还是不清楚树的实际用途。
一:场景:
1:现状
前几天我的一个大学同学负责的网站出现了严重的性能瓶颈,由于业务是写入和读取都是密集型,如果做缓存,时间间隔也只能在30s左
右,否则就会引起客户纠纷,所以同学也就没有做缓存,通过测试发现慢就慢在数据读取上面,总共需要10s,天啊...原来首页的加载关联
到了4张表,而且表数据中最多的在10w条以上,可以想象4张巨大表的关联,然后就是排序+范围查找等等相关的条件,让同学抓狂。
2:我个人的提供解决方案
① 读取问题
既然不能做缓存,那没办法,我们需要自己维护一套”内存数据库“,数据如何组织就靠我们的算法功底了,比如哈希适合等于性的查找,
树结构适合”范围查找“,lucene适合字符串的查找,我们在添加和更新的时候同时维护自己的内存数据库,最终杜绝表关联,老同学,还
是先应急,把常用的表灌倒内存,如果真想项目好的话,改架构吧...
② 添加问题
或许你的Add操作还没有达到瓶颈这一步,如果真的达到了那就看情况来进行”表切分“,”数据库切分“吧,让用户的Add或者Update
操作分流,虽然做起来很复杂,但是没办法,总比用户纠纷强吧,可对...
二:二叉查找树
正式切入主题,从上面的说明我们知道了二叉树非常适合于范围查找,关于树的基本定义,这里我就默认大家都知道,我就直接从
查找树说起了。
1:定义
查找树的定义非常简单,一句话就是左孩子比父节点小,右孩子比父节点大,还有一个特性就是”中序遍历“可以让结点有序。
2:树节点
为了具有通用性,我们定义成泛型模板,在每个结点中增加一个”数据附加域”。
1 /// <summary> 2 /// 二叉树节点 3 /// </summary> 4 /// <typeparam name="K"></typeparam> 5 /// <typeparam name="V"></typeparam> 6 public class BinaryNode<K, V> 7 { 8 /// <summary> 9 /// 节点元素 10 /// </summary> 11 public K key; 12 13 /// <summary> 14 /// 节点中的附加值 15 /// </summary> 16 public HashSet<V> attach = new HashSet<V>(); 17 18 /// <summary> 19 /// 左节点 20 /// </summary> 21 public BinaryNode<K, V> left; 22 23 /// <summary> 24 /// 右节点 25 /// </summary> 26 public BinaryNode<K, V> right; 27 28 public BinaryNode() { } 29 30 public BinaryNode(K key, V value, BinaryNode<K, V> left, BinaryNode<K, V> right) 31 { 32 //KV键值对 33 this.key = key; 34 this.attach.Add(value); 35 36 this.left = left; 37 this.right = right; 38 } 39 }
3:添加
根据查找树的性质我们可以很简单的写出Add的代码,一个一个的比呗,最终形成的效果图如下
这里存在一个“重复节点”的问题,比如说我在最后的树中再插入一个元素为15的结点,那么此时该怎么办,一般情况下,我们最好
不要在树中再追加一个重复结点,而是在“重复节点"的附加域中进行”+1“操作。
1 #region 添加操作 2 /// <summary> 3 /// 添加操作 4 /// </summary> 5 /// <param name="key"></param> 6 /// <param name="value"></param> 7 public void Add(K key, V value) 8 { 9 node = Add(key, value, node); 10 } 11 #endregion 12 13 #region 添加操作 14 /// <summary> 15 /// 添加操作 16 /// </summary> 17 /// <param name="key"></param> 18 /// <param name="value"></param> 19 /// <param name="tree"></param> 20 /// <returns></returns> 21 public BinaryNode<K, V> Add(K key, V value, BinaryNode<K, V> tree) 22 { 23 if (tree == null) 24 tree = new BinaryNode<K, V>(key, value, null, null); 25 26 //左子树 27 if (key.CompareTo(tree.key) < 0) 28 tree.left = Add(key, value, tree.left); 29 30 //右子树 31 if (key.CompareTo(tree.key) > 0) 32 tree.right = Add(key, value, tree.right); 33 34 //将value追加到附加值中(也可对应重复元素) 35 if (key.CompareTo(tree.key) == 0) 36 tree.attach.Add(value); 37 38 return tree; 39 } 40 #endregion
4:范围查找
这个才是我们使用二叉树的最终目的,既然是范围查找,我们就知道了一个”min“和”max“,其实实现起来也很简单,
第一步:我们要在树中找到min元素,当然min元素可能不存在,但是我们可以找到min的上界,耗费时间为O(logn)。
第二步:从min开始我们中序遍历寻找max的下界。耗费时间为m。m也就是匹配到的个数。
最后时间复杂度为M+logN,要知道普通的查找需要O(N)的时间,比如在21亿的数据规模下,匹配的元素可能有30个,那么最后
的结果也就是秒杀和几个小时甚至几天的巨大差异,后面我会做实验说明。
1 #region 树的指定范围查找 2 /// <summary> 3 /// 树的指定范围查找 4 /// </summary> 5 /// <param name="min"></param> 6 /// <param name="max"></param> 7 /// <returns></returns> 8 public HashSet<V> SearchRange(K min, K max) 9 { 10 HashSet<V> hashSet = new HashSet<V>(); 11 12 hashSet = SearchRange(min, max, hashSet, node); 13 14 return hashSet; 15 } 16 #endregion 17 18 #region 树的指定范围查找 19 /// <summary> 20 /// 树的指定范围查找 21 /// </summary> 22 /// <param name="range1"></param> 23 /// <param name="range2"></param> 24 /// <param name="tree"></param> 25 /// <returns></returns> 26 public HashSet<V> SearchRange(K min, K max, HashSet<V> hashSet, BinaryNode<K, V> tree) 27 { 28 if (tree == null) 29 return hashSet; 30 31 //遍历左子树(寻找下界) 32 if (min.CompareTo(tree.key) < 0) 33 SearchRange(min, max, hashSet, tree.left); 34 35 //当前节点是否在选定范围内 36 if (min.CompareTo(tree.key) <= 0 && max.CompareTo(tree.key) >= 0) 37 { 38 //等于这种情况 39 foreach (var item in tree.attach) 40 hashSet.Add(item); 41 } 42 43 //遍历右子树(两种情况:①:找min的下限 ②:必须在Max范围之内) 44 if (min.CompareTo(tree.key) > 0 || max.CompareTo(tree.key) > 0) 45 SearchRange(min, max, hashSet, tree.right); 46 47 return hashSet; 48 } 49 #endregion
5:删除
对于树来说,删除是最复杂的,主要考虑两种情况。
<1>单孩子的情况
这个比较简单,如果删除的节点有左孩子那就把左孩子顶上去,如果有右孩子就把右孩子顶上去,然后打完收工。
<2>左右都有孩子的情况。
首先可以这么想象,如果我们要删除一个数组的元素,那么我们在删除后会将其后面的一个元素顶到被删除的位置,如图
那么二叉树操作同样也是一样,我们根据”中序遍历“找到要删除结点的后一个结点,然后顶上去就行了,原理跟"数组”一样一样的。
同样这里也有一个注意的地方,在Add操作时,我们将重复元素的值追加到了“附加域”,那么在删除的时候,就可以先判断是
不是要“-1”操作而不是真正的删除节点,其实这里也就是“懒删除”,很有意思。
1 #region 删除当前树中的节点 2 /// <summary> 3 /// 删除当前树中的节点 4 /// </summary> 5 /// <param name="key"></param> 6 /// <returns></returns> 7 public void Remove(K key, V value) 8 { 9 node = Remove(key, value, node); 10 } 11 #endregion 12 13 #region 删除当前树中的节点 14 /// <summary> 15 /// 删除当前树中的节点 16 /// </summary> 17 /// <param name="key"></param> 18 /// <param name="tree"></param> 19 /// <returns></returns> 20 public BinaryNode<K, V> Remove(K key, V value, BinaryNode<K, V> tree) 21 { 22 if (tree == null) 23 return null; 24 25 //左子树 26 if (key.CompareTo(tree.key) < 0) 27 tree.left = Remove(key, value, tree.left); 28 29 //右子树 30 if (key.CompareTo(tree.key) > 0) 31 tree.right = Remove(key, value, tree.right); 32 33 /*相等的情况*/ 34 if (key.CompareTo(tree.key) == 0) 35 { 36 //判断里面的HashSet是否有多值 37 if (tree.attach.Count > 1) 38 { 39 //实现惰性删除 40 tree.attach.Remove(value); 41 } 42 else 43 { 44 //有两个孩子的情况 45 if (tree.left != null && tree.right != null) 46 { 47 //根据二叉树的中顺遍历,需要找到”有子树“的最小节点 48 tree.key = FindMin(tree.right).key; 49 50 //删除右子树的指定元素 51 tree.right = Remove(key, value, tree.right); 52 } 53 else 54 { 55 //单个孩子的情况 56 tree = tree.left == null ? tree.right : tree.left; 57 } 58 } 59 } 60 61 return tree; 62 } 63 #endregion
6天通吃树结构—— 第二天 平衡二叉树
上一篇我们聊过,二叉查找树不是严格的O(logN),导致了在真实场景中没有用武之地,谁也不愿意有O(N)的情况发生,
作为一名码农,肯定会希望能把“范围查找”做到地球人都不能优化的地步。
当有很多数据灌到我的树中时,我肯定会希望最好是以“完全二叉树”的形式展现,这样我才能做到“查找”是严格的O(logN),
比如把这种”树“调正到如下结构。
这里就涉及到了“树节点”的旋转,也是我们今天要聊到的内容。
一:平衡二叉树(AVL)
1:定义
父节点的左子树和右子树的高度之差不能大于1,也就是说不能高过1层,否则该树就失衡了,此时就要旋转节点,在
编码时,我们可以记录当前节点的高度,比如空节点是-1,叶子节点是0,非叶子节点的height往根节点递增,比如在下图
中我们认为树的高度为h=2。
1 #region 平衡二叉树节点 2 /// <summary> 3 /// 平衡二叉树节点 4 /// </summary> 5 /// <typeparam name="K"></typeparam> 6 /// <typeparam name="V"></typeparam> 7 public class AVLNode<K, V> 8 { 9 /// <summary> 10 /// 节点元素 11 /// </summary> 12 public K key; 13 14 /// <summary> 15 /// 增加一个高度信息 16 /// </summary> 17 public int height; 18 19 /// <summary> 20 /// 节点中的附加值 21 /// </summary> 22 public HashSet<V> attach = new HashSet<V>(); 23 24 /// <summary> 25 /// 左节点 26 /// </summary> 27 public AVLNode<K, V> left; 28 29 /// <summary> 30 /// 右节点 31 /// </summary> 32 public AVLNode<K, V> right; 33 34 public AVLNode() { } 35 36 public AVLNode(K key, V value, AVLNode<K, V> left, AVLNode<K, V> right) 37 { 38 //KV键值对 39 this.key = key; 40 this.attach.Add(value); 41 42 this.left = left; 43 this.right = right; 44 } 45 } 46 #endregion
2:旋转
节点再怎么失衡都逃不过4种情况,下面我们一一来看一下。
① 左左情况(左子树的左边节点)
我们看到,在向树中追加“节点1”的时候,根据定义我们知道这样会导致了“节点3"失衡,满足“左左情况“,可以这样想,把这
棵树比作齿轮,我们在“节点5”处把齿轮往下拉一个位置,也就变成了后面这样“平衡”的形式,如果用动画解释就最好理解了。
1 #region 第一种:左左旋转(单旋转) 2 /// <summary> 3 /// 第一种:左左旋转(单旋转) 4 /// </summary> 5 /// <param name="node"></param> 6 /// <returns></returns> 7 public AVLNode<K, V> RotateLL(AVLNode<K, V> node) 8 { 9 //top:需要作为顶级节点的元素 10 var top = node.left; 11 12 //先截断当前节点的左孩子 13 node.left = top.right; 14 15 //将当前节点作为temp的右孩子 16 top.right = node; 17 18 //计算当前两个节点的高度 19 node.height = Math.Max(Height(node.left), Height(node.right)) + 1; 20 top.height = Math.Max(Height(top.left), Height(top.right)) + 1; 21 22 return top; 23 } 24 #endregion
② 右右情况(右子树的右边节点)
同样,”节点5“满足”右右情况“,其实我们也看到,这两种情况是一种镜像,当然操作方式也大同小异,我们在”节点1“的地方
将树往下拉一位,最后也就形成了我们希望的平衡效果。
1 #region 第二种:右右旋转(单旋转) 2 /// <summary> 3 /// 第二种:右右旋转(单旋转) 4 /// </summary> 5 /// <param name="node"></param> 6 /// <returns></returns> 7 public AVLNode<K, V> RotateRR(AVLNode<K, V> node) 8 { 9 //top:需要作为顶级节点的元素 10 var top = node.right; 11 12 //先截断当前节点的右孩子 13 node.right = top.left; 14 15 //将当前节点作为temp的右孩子 16 top.left = node; 17 18 //计算当前两个节点的高度 19 node.height = Math.Max(Height(node.left), Height(node.right)) + 1; 20 top.height = Math.Max(Height(top.left), Height(top.right)) + 1; 21 22 return top; 23 } 24 #endregion
③左右情况(左子树的右边节点)
从图中我们可以看到,当我们插入”节点3“时,“节点5”处失衡,注意,找到”失衡点“是非常重要的,当面对”左右情况“时,我们将
失衡点的左子树进行"右右情况旋转",然后进行”左左情况旋转“,经过这样两次的旋转就OK了,很有意思,对吧。
1 #region 第三种:左右旋转(双旋转) 2 /// <summary> 3 /// 第三种:左右旋转(双旋转) 4 /// </summary> 5 /// <param name="node"></param> 6 /// <returns></returns> 7 public AVLNode<K, V> RotateLR(AVLNode<K, V> node) 8 { 9 //先进行RR旋转 10 node.left = RotateRR(node.left); 11 12 //再进行LL旋转 13 return RotateLL(node); 14 } 15 #endregion
④右左情况(右子树的左边节点)
这种情况和“情景3”也是一种镜像关系,很简单,我们找到了”节点15“是失衡点,然后我们将”节点15“的右子树进行”左左情况旋转“,
然后进行”右右情况旋转“,最终得到了我们满意的平衡。
1 #region 第四种:右左旋转(双旋转) 2 /// <summary> 3 /// 第四种:右左旋转(双旋转) 4 /// </summary> 5 /// <param name="node"></param> 6 /// <returns></returns> 7 public AVLNode<K, V> RotateRL(AVLNode<K, V> node) 8 { 9 //执行左左旋转 10 node.right = RotateLL(node.right); 11 12 //再执行右右旋转 13 return RotateRR(node); 14 15 } 16 #endregion
3:添加
如果我们理解了上面的这几种旋转,那么添加方法简直是轻而易举,出现了哪一种情况调用哪一种方法而已。
1 #region 添加操作 2 /// <summary> 3 /// 添加操作 4 /// </summary> 5 /// <param name="key"></param> 6 /// <param name="value"></param> 7 /// <param name="tree"></param> 8 /// <returns></returns> 9 public AVLNode<K, V> Add(K key, V value, AVLNode<K, V> tree) 10 { 11 if (tree == null) 12 tree = new AVLNode<K, V>(key, value, null, null); 13 14 //左子树 15 if (key.CompareTo(tree.key) < 0) 16 { 17 tree.left = Add(key, value, tree.left); 18 19 //如果说相差等于2就说明这棵树需要旋转了 20 if (Height(tree.left) - Height(tree.right) == 2) 21 { 22 //说明此时是左左旋转 23 if (key.CompareTo(tree.left.key) < 0) 24 { 25 tree = RotateLL(tree); 26 } 27 else 28 { 29 //属于左右旋转 30 tree = RotateLR(tree); 31 } 32 } 33 } 34 35 //右子树 36 if (key.CompareTo(tree.key) > 0) 37 { 38 tree.right = Add(key, value, tree.right); 39 40 if ((Height(tree.right) - Height(tree.left) == 2)) 41 { 42 //此时是右右旋转 43 if (key.CompareTo(tree.right.key) > 0) 44 { 45 tree = RotateRR(tree); 46 } 47 else 48 { 49 //属于右左旋转 50 tree = RotateRL(tree); 51 } 52 } 53 } 54 55 //将value追加到附加值中(也可对应重复元素) 56 if (key.CompareTo(tree.key) == 0) 57 tree.attach.Add(value); 58 59 //计算高度 60 tree.height = Math.Max(Height(tree.left), Height(tree.right)) + 1; 61 62 return tree; 63 } 64 #endregion4:删除
删除方法跟添加方法也类似,当删除一个结点的时候,可能会引起祖先结点的失衡,所以在每次”结点“回退的时候计算结点高度。
1 #region 删除当前树中的节点 2 /// <summary> 3 /// 删除当前树中的节点 4 /// </summary> 5 /// <param name="key"></param> 6 /// <param name="tree"></param> 7 /// <returns></returns> 8 public AVLNode<K, V> Remove(K key, V value, AVLNode<K, V> tree) 9 { 10 if (tree == null) 11 return null; 12 13 //左子树 14 if (key.CompareTo(tree.key) < 0) 15 { 16 tree.left = Remove(key, value, tree.left); 17 18 //如果说相差等于2就说明这棵树需要旋转了 19 if (Height(tree.left) - Height(tree.right) == 2) 20 { 21 //说明此时是左左旋转 22 if (key.CompareTo(tree.left.key) < 0) 23 { 24 tree = RotateLL(tree); 25 } 26 else 27 { 28 //属于左右旋转 29 tree = RotateLR(tree); 30 } 31 } 32 } 33 //右子树 34 if (key.CompareTo(tree.key) > 0) 35 { 36 tree.right = Remove(key, value, tree.right); 37 38 if ((Height(tree.right) - Height(tree.left) == 2)) 39 { 40 //此时是右右旋转 41 if (key.CompareTo(tree.right.key) > 0) 42 { 43 tree = RotateRR(tree); 44 } 45 else 46 { 47 //属于右左旋转 48 tree = RotateRL(tree); 49 } 50 } 51 } 52 /*相等的情况*/ 53 if (key.CompareTo(tree.key) == 0) 54 { 55 //判断里面的HashSet是否有多值 56 if (tree.attach.Count > 1) 57 { 58 //实现惰性删除 59 tree.attach.Remove(value); 60 } 61 else 62 { 63 //有两个孩子的情况 64 if (tree.left != null && tree.right != null) 65 { 66 //根据平衡二叉树的中顺遍历,需要找到”有子树“的最小节点 67 tree.key = FindMin(tree.right).key; 68 69 //删除右子树的指定元素 70 tree.right = Remove(tree.key, value, tree.right); 71 } 72 else 73 { 74 //自减高度 75 tree = tree.left == null ? tree.right : tree.left; 76 77 //如果删除的是叶子节点直接返回 78 if (tree == null) 79 return null; 80 } 81 } 82 } 83 84 //统计高度 85 tree.height = Math.Max(Height(tree.left), Height(tree.right)) + 1; 86 87 return tree; 88 } 89 #endregion5: 测试
不像上一篇不能在二叉树中灌有序数据,平衡二叉树就没关系了,我们的需求是检索2012-7-30 4:00:00 到 2012-7-30 5:00:00
的登陆用户的ID,数据量在500w,看看平衡二叉树是如何秒杀对手。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Diagnostics;
namespace DataStruct
{
class Program
{
static void Main(string[] args)
{
AVLTree<int, int> avl = new AVLTree<int, int>();
Dictionary<DateTime, int> dic = new Dictionary<DateTime, int>();
AVLTree<DateTime, int> tree = new AVLTree<DateTime, int>();
//500w
for (int i = 1; i < 5000000; i++)
{
dic.Add(DateTime.Now.AddMinutes(i), i);
tree.Add(DateTime.Now.AddMinutes(i), i);
}
//检索2012-7-30 4:00:00 到 2012-7-30 5:00:00的登陆人数
var min = Convert.ToDateTime("2012/7/30 4:00:00");
var max = Convert.ToDateTime("2012/7/30 5:00:00");
var watch = Stopwatch.StartNew();
var result1 = dic.Keys.Where(i => i >= min && i <= max).Select(i => dic[i]).ToList();
watch.Stop();
Console.WriteLine("字典查找耗费时间:{0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
var result2 = tree.SearchRange(min, max);
watch.Stop();
Console.WriteLine("平衡二叉树查找耗费时间:{0}ms", watch.ElapsedMilliseconds);
}
}
#region 平衡二叉树节点
/// <summary>
/// 平衡二叉树节点
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
public class AVLNode<K, V>
{
/// <summary>
/// 节点元素
/// </summary>
public K key;
/// <summary>
/// 增加一个高度信息
/// </summary>
public int height;
/// <summary>
/// 节点中的附加值
/// </summary>
public HashSet<V> attach = new HashSet<V>();
/// <summary>
/// 左节点
/// </summary>
public AVLNode<K, V> left;
/// <summary>
/// 右节点
/// </summary>
public AVLNode<K, V> right;
public AVLNode() { }
public AVLNode(K key, V value, AVLNode<K, V> left, AVLNode<K, V> right)
{
//KV键值对
this.key = key;
this.attach.Add(value);
this.left = left;
this.right = right;
}
}
#endregion
public class AVLTree<K, V> where K : IComparable
{
public AVLNode<K, V> node = null;
#region 添加操作
/// <summary>
/// 添加操作
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(K key, V value)
{
node = Add(key, value, node);
}
#endregion
#region 添加操作
/// <summary>
/// 添加操作
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="tree"></param>
/// <returns></returns>
public AVLNode<K, V> Add(K key, V value, AVLNode<K, V> tree)
{
if (tree == null)
tree = new AVLNode<K, V>(key, value, null, null);
//左子树
if (key.CompareTo(tree.key) < 0)
{
tree.left = Add(key, value, tree.left);
//如果说相差等于2就说明这棵树需要旋转了
if (Height(tree.left) - Height(tree.right) == 2)
{
//说明此时是左左旋转
if (key.CompareTo(tree.left.key) < 0)
{
tree = RotateLL(tree);
}
else
{
//属于左右旋转
tree = RotateLR(tree);
}
}
}
//右子树
if (key.CompareTo(tree.key) > 0)
{
tree.right = Add(key, value, tree.right);
if ((Height(tree.right) - Height(tree.left) == 2))
{
//此时是右右旋转
if (key.CompareTo(tree.right.key) > 0)
{
tree = RotateRR(tree);
}
else
{
//属于右左旋转
tree = RotateRL(tree);
}
}
}
//将value追加到附加值中(也可对应重复元素)
if (key.CompareTo(tree.key) == 0)
tree.attach.Add(value);
//计算高度
tree.height = Math.Max(Height(tree.left), Height(tree.right)) + 1;
return tree;
}
#endregion
#region 计算当前节点的高度
/// <summary>
/// 计算当前节点的高度
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public int Height(AVLNode<K, V> node)
{
return node == null ? -1 : node.height;
}
#endregion
#region 第一种:左左旋转(单旋转)
/// <summary>
/// 第一种:左左旋转(单旋转)
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public AVLNode<K, V> RotateLL(AVLNode<K, V> node)
{
//top:需要作为顶级节点的元素
var top = node.left;
//先截断当前节点的左孩子
node.left = top.right;
//将当前节点作为temp的右孩子
top.right = node;
//计算当前两个节点的高度
node.height = Math.Max(Height(node.left), Height(node.right)) + 1;
top.height = Math.Max(Height(top.left), Height(top.right)) + 1;
return top;
}
#endregion
#region 第二种:右右旋转(单旋转)
/// <summary>
/// 第二种:右右旋转(单旋转)
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public AVLNode<K, V> RotateRR(AVLNode<K, V> node)
{
//top:需要作为顶级节点的元素
var top = node.right;
//先截断当前节点的右孩子
node.right = top.left;
//将当前节点作为temp的右孩子
top.left = node;
//计算当前两个节点的高度
node.height = Math.Max(Height(node.left), Height(node.right)) + 1;
top.height = Math.Max(Height(top.left), Height(top.right)) + 1;
return top;
}
#endregion
#region 第三种:左右旋转(双旋转)
/// <summary>
/// 第三种:左右旋转(双旋转)
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public AVLNode<K, V> RotateLR(AVLNode<K, V> node)
{
//先进行RR旋转
node.left = RotateRR(node.left);
//再进行LL旋转
return RotateLL(node);
}
#endregion
#region 第四种:右左旋转(双旋转)
/// <summary>
/// 第四种:右左旋转(双旋转)
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public AVLNode<K, V> RotateRL(AVLNode<K, V> node)
{
//执行左左旋转
node.right = RotateLL(node.right);
//再执行右右旋转
return RotateRR(node);
}
#endregion
#region 是否包含指定元素
/// <summary>
/// 是否包含指定元素
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Contain(K key)
{
return Contain(key, node);
}
#endregion
#region 是否包含指定元素
/// <summary>
/// 是否包含指定元素
/// </summary>
/// <param name="key"></param>
/// <param name="tree"></param>
/// <returns></returns>
public bool Contain(K key, AVLNode<K, V> tree)
{
if (tree == null)
return false;
//左子树
if (key.CompareTo(tree.key) < 0)
return Contain(key, tree.left);
//右子树
if (key.CompareTo(tree.key) > 0)
return Contain(key, tree.right);
return true;
}
#endregion
#region 树的指定范围查找
/// <summary>
/// 树的指定范围查找
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public HashSet<V> SearchRange(K min, K max)
{
HashSet<V> hashSet = new HashSet<V>();
hashSet = SearchRange(min, max, hashSet, node);
return hashSet;
}
#endregion
#region 树的指定范围查找
/// <summary>
/// 树的指定范围查找
/// </summary>
/// <param name="range1"></param>
/// <param name="range2"></param>
/// <param name="tree"></param>
/// <returns></returns>
public HashSet<V> SearchRange(K min, K max, HashSet<V> hashSet, AVLNode<K, V> tree)
{
if (tree == null)
return hashSet;
//遍历左子树(寻找下界)
if (min.CompareTo(tree.key) < 0)
SearchRange(min, max, hashSet, tree.left);
//当前节点是否在选定范围内
if (min.CompareTo(tree.key) <= 0 && max.CompareTo(tree.key) >= 0)
{
//等于这种情况
foreach (var item in tree.attach)
hashSet.Add(item);
}
//遍历右子树(两种情况:①:找min的下限 ②:必须在Max范围之内)
if (min.CompareTo(tree.key) > 0 || max.CompareTo(tree.key) > 0)
SearchRange(min, max, hashSet, tree.right);
return hashSet;
}
#endregion
#region 找到当前树的最小节点
/// <summary>
/// 找到当前树的最小节点
/// </summary>
/// <returns></returns>
public AVLNode<K, V> FindMin()
{
return FindMin(node);
}
#endregion
#region 找到当前树的最小节点
/// <summary>
/// 找到当前树的最小节点
/// </summary>
/// <param name="tree"></param>
/// <returns></returns>
public AVLNode<K, V> FindMin(AVLNode<K, V> tree)
{
if (tree == null)
return null;
if (tree.left == null)
return tree;
return FindMin(tree.left);
}
#endregion
#region 找到当前树的最大节点
/// <summary>
/// 找到当前树的最大节点
/// </summary>
/// <returns></returns>
public AVLNode<K, V> FindMax()
{
return FindMin(node);
}
#endregion
#region 找到当前树的最大节点
/// <summary>
/// 找到当前树的最大节点
/// </summary>
/// <param name="tree"></param>
/// <returns></returns>
public AVLNode<K, V> FindMax(AVLNode<K, V> tree)
{
if (tree == null)
return null;
if (tree.right == null)
return tree;
return FindMax(tree.right);
}
#endregion
#region 删除当前树中的节点
/// <summary>
/// 删除当前树中的节点
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public void Remove(K key, V value)
{
node = Remove(key, value, node);
}
#endregion
#region 删除当前树中的节点
/// <summary>
/// 删除当前树中的节点
/// </summary>
/// <param name="key"></param>
/// <param name="tree"></param>
/// <returns></returns>
public AVLNode<K, V> Remove(K key, V value, AVLNode<K, V> tree)
{
if (tree == null)
return null;
//左子树
if (key.CompareTo(tree.key) < 0)
{
tree.left = Remove(key, value, tree.left);
//如果说相差等于2就说明这棵树需要旋转了
if (Height(tree.left) - Height(tree.right) == 2)
{
//说明此时是左左旋转
if (key.CompareTo(tree.left.key) < 0)
{
tree = RotateLL(tree);
}
else
{
//属于左右旋转
tree = RotateLR(tree);
}
}
}
//右子树
if (key.CompareTo(tree.key) > 0)
{
tree.right = Remove(key, value, tree.right);
if ((Height(tree.right) - Height(tree.left) == 2))
{
//此时是右右旋转
if (key.CompareTo(tree.right.key) > 0)
{
tree = RotateRR(tree);
}
else
{
//属于右左旋转
tree = RotateRL(tree);
}
}
}
/*相等的情况*/
if (key.CompareTo(tree.key) == 0)
{
//判断里面的HashSet是否有多值
if (tree.attach.Count > 1)
{
//实现惰性删除
tree.attach.Remove(value);
}
else
{
//有两个孩子的情况
if (tree.left != null && tree.right != null)
{
//根据平衡二叉树的中顺遍历,需要找到”有子树“的最小节点
tree.key = FindMin(tree.right).key;
//删除右子树的指定元素
tree.right = Remove(tree.key, value, tree.right);
}
else
{
//自减高度
tree = tree.left == null ? tree.right : tree.left;
//如果删除的是叶子节点直接返回
if (tree == null)
return null;
}
}
}
//统计高度
tree.height = Math.Max(Height(tree.left), Height(tree.right)) + 1;
return tree;
}
#endregion
}
}
wow,相差98倍,这个可不是一个级别啊...AVL神器。
6天通吃树结构—— 第三天 Treap树
我们知道,二叉查找树相对来说比较容易形成最坏的链表情况,所以前辈们想尽了各种优化策略,包括AVL,红黑,以及今天
要讲的Treap树。
Treap树算是一种简单的优化策略,这名字大家也能猜到,树和堆的合体,其实原理比较简单,在树中维护一个"优先级“,”优先级“
采用随机数的方法,但是”优先级“必须满足根堆的性质,当然是“大根堆”或者“小根堆”都无所谓,比如下面的一棵树:
从树中我们可以看到:
①:节点中的key满足“二叉查找树”。
②:节点中的“优先级”满足小根堆。
一:基本操作
1:定义
1 #region Treap树节点 2 /// <summary> 3 /// Treap树 4 /// </summary> 5 /// <typeparam name="K"></typeparam> 6 /// <typeparam name="V"></typeparam> 7 public class TreapNode<K, V> 8 { 9 /// <summary> 10 /// 节点元素 11 /// </summary> 12 public K key; 13 14 /// <summary> 15 /// 优先级(采用随机数) 16 /// </summary> 17 public int priority; 18 19 /// <summary> 20 /// 节点中的附加值 21 /// </summary> 22 public HashSet<V> attach = new HashSet<V>(); 23 24 /// <summary> 25 /// 左节点 26 /// </summary> 27 public TreapNode<K, V> left; 28 29 /// <summary> 30 /// 右节点 31 /// </summary> 32 public TreapNode<K, V> right; 33 34 public TreapNode() { } 35 36 public TreapNode(K key, V value, TreapNode<K, V> left, TreapNode<K, V> right) 37 { 38 //KV键值对 39 this.key = key; 40 this.priority = new Random(DateTime.Now.Millisecond).Next(0,int.MaxValue); 41 this.attach.Add(value); 42 43 this.left = left; 44 this.right = right; 45 } 46 } 47 #endregion节点里面定义了一个priority作为“堆定义”的旋转因子,因子采用“随机数“。
2:添加
首先我们知道各个节点的“优先级”是采用随机数的方法,那么就存在一个问题,当我们插入一个节点后,优先级不满足“堆定义"的
时候我们该怎么办,前辈说此时需要旋转,直到满足堆定义为止。
旋转有两种方式,如果大家玩转了AVL,那么对Treap中的旋转的理解轻而易举。
①: 左左情况旋转
从图中可以看出,当我们插入“节点12”的时候,此时“堆性质”遭到破坏,必须进行旋转,我们发现优先级是6<9,所以就要进行
左左情况旋转,最终也就形成了我们需要的结果。
②: 右右情况旋转
既然理解了”左左情况旋转“,右右情况也是同样的道理,优先级中发现“6<9",进行”右右旋转“最终达到我们要的效果。
1 #region 添加操作 2 /// <summary> 3 /// 添加操作 4 /// </summary> 5 /// <param name="key"></param> 6 /// <param name="value"></param> 7 public void Add(K key, V value) 8 { 9 node = Add(key, value, node); 10 } 11 #endregion 12 13 #region 添加操作 14 /// <summary> 15 /// 添加操作 16 /// </summary> 17 /// <param name="key"></param> 18 /// <param name="value"></param> 19 /// <param name="tree"></param> 20 /// <returns></returns> 21 public TreapNode<K, V> Add(K key, V value, TreapNode<K, V> tree) 22 { 23 if (tree == null) 24 tree = new TreapNode<K, V>(key, value, null, null); 25 26 //左子树 27 if (key.CompareTo(tree.key) < 0) 28 { 29 tree.left = Add(key, value, tree.left); 30 31 //根据小根堆性质,需要”左左情况旋转” 32 if (tree.left.priority < tree.priority) 33 { 34 tree = RotateLL(tree); 35 } 36 } 37 38 //右子树 39 if (key.CompareTo(tree.key) > 0) 40 { 41 tree.right = Add(key, value, tree.right); 42 43 //根据小根堆性质,需要”右右情况旋转” 44 if (tree.right.priority < tree.priority) 45 { 46 tree = RotateRR(tree); 47 } 48 } 49 50 //将value追加到附加值中(也可对应重复元素) 51 if (key.CompareTo(tree.key) == 0) 52 tree.attach.Add(value); 53 54 return tree; 55 } 56 #endregion
3:删除
跟普通的二叉查找树一样,删除结点存在三种情况。
①:叶子结点
跟普通查找树一样,直接释放本节点即可。
②:单孩子结点
跟普通查找树一样操作。
③:满孩子结点
其实在treap中删除满孩子结点有两种方式。
第一种:跟普通的二叉查找树一样,找到“右子树”的最左结点(15),拷贝元素的值,但不拷贝元素的优先级,然后在右子树中
删除“结点15”即可,最终效果如下图。
第二种:将”结点下旋“,直到该节点不是”满孩子的情况“,该赋null的赋null,该将孩子结点顶上的就顶上,如下图:
当然从理论上来说,第二种删除方法更合理,这里我写的就是第二种情况的代码。
1 #region 删除当前树中的节点 2 /// <summary> 3 /// 删除当前树中的节点 4 /// </summary> 5 /// <param name="key"></param> 6 /// <returns></returns> 7 public void Remove(K key, V value) 8 { 9 node = Remove(key, value, node); 10 } 11 #endregion 12 13 #region 删除当前树中的节点 14 /// <summary> 15 /// 删除当前树中的节点 16 /// </summary> 17 /// <param name="key"></param> 18 /// <param name="tree"></param> 19 /// <returns></returns> 20 public TreapNode<K, V> Remove(K key, V value, TreapNode<K, V> tree) 21 { 22 if (tree == null) 23 return null; 24 25 //左子树 26 if (key.CompareTo(tree.key) < 0) 27 { 28 tree.left = Remove(key, value, tree.left); 29 } 30 //右子树 31 if (key.CompareTo(tree.key) > 0) 32 { 33 tree.right = Remove(key, value, tree.right); 34 } 35 /*相等的情况*/ 36 if (key.CompareTo(tree.key) == 0) 37 { 38 //判断里面的HashSet是否有多值 39 if (tree.attach.Count > 1) 40 { 41 //实现惰性删除 42 tree.attach.Remove(value); 43 } 44 else 45 { 46 //有两个孩子的情况 47 if (tree.left != null && tree.right != null) 48 { 49 //如果左孩子的优先级低就需要“左旋” 50 if (tree.left.priority < tree.right.priority) 51 { 52 tree = RotateLL(tree); 53 } 54 else 55 { 56 //否则“右旋” 57 tree = RotateRR(tree); 58 } 59 60 //继续旋转 61 tree = Remove(key, value, tree); 62 } 63 else 64 { 65 //如果旋转后已经变成了叶子节点则直接删除 66 if (tree == null) 67 return null; 68 69 //最后就是单支树 70 tree = tree.left == null ? tree.right : tree.left; 71 } 72 } 73 } 74 75 return tree; 76 } 77 #endregion
4:总结
treap树在CURD中是期望的logN,由于我们加了”优先级“,所以会出现”链表“的情况几乎不存在,但是他的Add和Remove相比严格的
平衡二叉树有更少的旋转操作,可以说性能是在”普通二叉树“和”平衡二叉树“之间。
最后是总运行代码,不过这里我就不做测试了。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace DataStruct 7 { 8 #region Treap树节点 9 /// <summary> 10 /// Treap树 11 /// </summary> 12 /// <typeparam name="K"></typeparam> 13 /// <typeparam name="V"></typeparam> 14 public class TreapNode<K, V> 15 { 16 /// <summary> 17 /// 节点元素 18 /// </summary> 19 public K key; 20 21 /// <summary> 22 /// 优先级(采用随机数) 23 /// </summary> 24 public int priority; 25 26 /// <summary> 27 /// 节点中的附加值 28 /// </summary> 29 public HashSet<V> attach = new HashSet<V>(); 30 31 /// <summary> 32 /// 左节点 33 /// </summary> 34 public TreapNode<K, V> left; 35 36 /// <summary> 37 /// 右节点 38 /// </summary> 39 public TreapNode<K, V> right; 40 41 public TreapNode() { } 42 43 public TreapNode(K key, V value, TreapNode<K, V> left, TreapNode<K, V> right) 44 { 45 //KV键值对 46 this.key = key; 47 this.priority = new Random(DateTime.Now.Millisecond).Next(0,int.MaxValue); 48 this.attach.Add(value); 49 50 this.left = left; 51 this.right = right; 52 } 53 } 54 #endregion 55 56 public class TreapTree<K, V> where K : IComparable 57 { 58 public TreapNode<K, V> node = null; 59 60 #region 添加操作 61 /// <summary> 62 /// 添加操作 63 /// </summary> 64 /// <param name="key"></param> 65 /// <param name="value"></param> 66 public void Add(K key, V value) 67 { 68 node = Add(key, value, node); 69 } 70 #endregion 71 72 #region 添加操作 73 /// <summary> 74 /// 添加操作 75 /// </summary> 76 /// <param name="key"></param> 77 /// <param name="value"></param> 78 /// <param name="tree"></param> 79 /// <returns></returns> 80 public TreapNode<K, V> Add(K key, V value, TreapNode<K, V> tree) 81 { 82 if (tree == null) 83 tree = new TreapNode<K, V>(key, value, null, null); 84 85 //左子树 86 if (key.CompareTo(tree.key) < 0) 87 { 88 tree.left = Add(key, value, tree.left); 89 90 //根据小根堆性质,需要”左左情况旋转” 91 if (tree.left.priority < tree.priority) 92 { 93 tree = RotateLL(tree); 94 } 95 } 96 97 //右子树 98 if (key.CompareTo(tree.key) > 0) 99 { 100 tree.right = Add(key, value, tree.right); 101 102 //根据小根堆性质,需要”右右情况旋转” 103 if (tree.right.priority < tree.priority) 104 { 105 tree = RotateRR(tree); 106 } 107 } 108 109 //将value追加到附加值中(也可对应重复元素) 110 if (key.CompareTo(tree.key) == 0) 111 tree.attach.Add(value); 112 113 return tree; 114 } 115 #endregion 116 117 #region 第一种:左左旋转(单旋转) 118 /// <summary> 119 /// 第一种:左左旋转(单旋转) 120 /// </summary> 121 /// <param name="node"></param> 122 /// <returns></returns> 123 public TreapNode<K, V> RotateLL(TreapNode<K, V> node) 124 { 125 //top:需要作为顶级节点的元素 126 var top = node.left; 127 128 //先截断当前节点的左孩子 129 node.left = top.right; 130 131 //将当前节点作为temp的右孩子 132 top.right = node; 133 134 return top; 135 } 136 #endregion 137 138 #region 第二种:右右旋转(单旋转) 139 /// <summary> 140 /// 第二种:右右旋转(单旋转) 141 /// </summary> 142 /// <param name="node"></param> 143 /// <returns></returns> 144 public TreapNode<K, V> RotateRR(TreapNode<K, V> node) 145 { 146 //top:需要作为顶级节点的元素 147 var top = node.right; 148 149 //先截断当前节点的右孩子 150 node.right = top.left; 151 152 //将当前节点作为temp的右孩子 153 top.left = node; 154 155 return top; 156 } 157 #endregion 158 159 #region 树的指定范围查找 160 /// <summary> 161 /// 树的指定范围查找 162 /// </summary> 163 /// <param name="min"></param> 164 /// <param name="max"></param> 165 /// <returns></returns> 166 public HashSet<V> SearchRange(K min, K max) 167 { 168 HashSet<V> hashSet = new HashSet<V>(); 169 170 hashSet = SearchRange(min, max, hashSet, node); 171 172 return hashSet; 173 } 174 #endregion 175 176 #region 树的指定范围查找 177 /// <summary> 178 /// 树的指定范围查找 179 /// </summary> 180 /// <param name="range1"></param> 181 /// <param name="range2"></param> 182 /// <param name="tree"></param> 183 /// <returns></returns> 184 public HashSet<V> SearchRange(K min, K max, HashSet<V> hashSet, TreapNode<K, V> tree) 185 { 186 if (tree == null) 187 return hashSet; 188 189 //遍历左子树(寻找下界) 190 if (min.CompareTo(tree.key) < 0) 191 SearchRange(min, max, hashSet, tree.left); 192 193 //当前节点是否在选定范围内 194 if (min.CompareTo(tree.key) <= 0 && max.CompareTo(tree.key) >= 0) 195 { 196 //等于这种情况 197 foreach (var item in tree.attach) 198 hashSet.Add(item); 199 } 200 201 //遍历右子树(两种情况:①:找min的下限 ②:必须在Max范围之内) 202 if (min.CompareTo(tree.key) > 0 || max.CompareTo(tree.key) > 0) 203 SearchRange(min, max, hashSet, tree.right); 204 205 return hashSet; 206 } 207 #endregion 208 209 #region 找到当前树的最小节点 210 /// <summary> 211 /// 找到当前树的最小节点 212 /// </summary> 213 /// <returns></returns> 214 public TreapNode<K, V> FindMin() 215 { 216 return FindMin(node); 217 } 218 #endregion 219 220 #region 找到当前树的最小节点 221 /// <summary> 222 /// 找到当前树的最小节点 223 /// </summary> 224 /// <param name="tree"></param> 225 /// <returns></returns> 226 public TreapNode<K, V> FindMin(TreapNode<K, V> tree) 227 { 228 if (tree == null) 229 return null; 230 231 if (tree.left == null) 232 return tree; 233 234 return FindMin(tree.left); 235 } 236 #endregion 237 238 #region 找到当前树的最大节点 239 /// <summary> 240 /// 找到当前树的最大节点 241 /// </summary> 242 /// <returns></returns> 243 public TreapNode<K, V> FindMax() 244 { 245 return FindMin(node); 246 } 247 #endregion 248 249 #region 找到当前树的最大节点 250 /// <summary> 251 /// 找到当前树的最大节点 252 /// </summary> 253 /// <param name="tree"></param> 254 /// <returns></returns> 255 public TreapNode<K, V> FindMax(TreapNode<K, V> tree) 256 { 257 if (tree == null) 258 return null; 259 260 if (tree.right == null) 261 return tree; 262 263 return FindMax(tree.right); 264 } 265 #endregion 266 267 #region 删除当前树中的节点 268 /// <summary> 269 /// 删除当前树中的节点 270 /// </summary> 271 /// <param name="key"></param> 272 /// <returns></returns> 273 public void Remove(K key, V value) 274 { 275 node = Remove(key, value, node); 276 } 277 #endregion 278 279 #region 删除当前树中的节点 280 /// <summary> 281 /// 删除当前树中的节点 282 /// </summary> 283 /// <param name="key"></param> 284 /// <param name="tree"></param> 285 /// <returns></returns> 286 public TreapNode<K, V> Remove(K key, V value, TreapNode<K, V> tree) 287 { 288 if (tree == null) 289 return null; 290 291 //左子树 292 if (key.CompareTo(tree.key) < 0) 293 { 294 tree.left = Remove(key, value, tree.left); 295 } 296 //右子树 297 if (key.CompareTo(tree.key) > 0) 298 { 299 tree.right = Remove(key, value, tree.right); 300 } 301 /*相等的情况*/ 302 if (key.CompareTo(tree.key) == 0) 303 { 304 //判断里面的HashSet是否有多值 305 if (tree.attach.Count > 1) 306 { 307 //实现惰性删除 308 tree.attach.Remove(value); 309 } 310 else 311 { 312 //有两个孩子的情况 313 if (tree.left != null && tree.right != null) 314 { 315 //如果左孩子的优先级低就需要“左旋” 316 if (tree.left.priority < tree.right.priority) 317 { 318 tree = RotateLL(tree); 319 } 320 else 321 { 322 //否则“右旋” 323 tree = RotateRR(tree); 324 } 325 326 //继续旋转 327 tree = Remove(key, value, tree); 328 } 329 else 330 { 331 //如果旋转后已经变成了叶子节点则直接删除 332 if (tree == null) 333 return null; 334 335 //最后就是单支树 336 tree = tree.left == null ? tree.right : tree.left; 337 } 338 } 339 } 340 341 return tree; 342 } 343 #endregion 344 } 345 }