Treap――堆和二叉树的完美结合,性价比极值的搜索树
大家好,今天和大家聊一个新的数据结构,叫做Treap。
Treap本质上也是一颗BST(平衡二叉搜索树),和我们之前介绍的SBT是一样的。但是Treap维持平衡的方法和SBT不太一样,有些许区别,相比来说呢,Treap的原理还要再简单一些,所以之前在竞赛当中不允许使用STL的时候,我们通常都会手写一棵Treap来代替。
Treap的基本原理
既然是平衡二叉搜索树,关键点就在于平衡,那么重点自然是如何维护树的平衡。
在Treap当中,维护平衡非常简单,只有一句话,就是通过维护小顶堆的形式来维持树的平衡。Treap也正是因此得名,因为它是Tree和Heap的结合体。
我们来看下Treap当中节点的结构:
class TreapNode(TreeNode): """ TreeNode: The node class of treap tree. Paramters: key: The key of node, can be treated as the key of dictionary value: The value of node, can be treated as the value of dictionary priority: The priority of node, specially for treap structure, describe the priority of the node in the treap. lchild: The&nbsTrp;left child of node rchild: The right child of node father: The parent of node, incase that we need to remove or rotate the node in the treap, so we need father parameter to mark the address of the parent """ def __init__(self, key=None, value=None, lchild=None, rchild=None, father=None, priority=None): super().__init__(key, value, lchild, rchild, father) self._priority = priority @property def priority(self): return self._priority @priority.setter def priority(self, preaiority): self._priority = priority def __str__(self): return 'key={}, value={}'.format(self.key, self.value)
这里的TreeNode是我抽象出来的树结构通用的Node,当中包含key、value、lchild、rchild和father。TreapNode其实就是在此基础上增加了一个priority属性。
之所以要增加这个priority属性是为了维护它堆的性质,通过维护这个堆的性质来保持树的平衡。具体的操作方法,请往下看。
Treap的增删改查
插入
首先来讲Treap的插入元素的操作,其实插入元素的操作非常简单,就是普通BST插入元素的操作。唯一的问题是如何维持树的平衡。
我们前文说了,我们是通过维持堆的性质来保持平衡的,那么自然又会有一个新的问题。为什么维持堆的性质可以保证平衡呢?
答案很简单,因为我们在插入的时候,需要对每一个插入的Node随机附上一个priority。堆就是用来维护这个priority的,保证树根一定拥有最小的priority。正是由于这个priority是随机的,我们可以保证整棵树蜕化成线性的概率降到无穷低。
当我们插入元素之后发现破坏了堆的性质,那么我们需要通过旋转操作来维护。举个简单的例子,在下图当中,如果B节点的priority比D要小,为了保证堆的性质,需要将B和D进行互换。由于直接互换会破坏BST的性质,所以我们采取旋转的操作。
旋转之后我们发现B和D互换了位置,并且旋转之后的A和E的priority都是大于D的,所以旋转之后我们整棵树依然维持了性质。
右旋的情况也是一样的,其实我们观察一下会发现,要交换左孩子和父亲需要右旋,如果是要交换右孩子和父亲,则需要左旋。
整个插入的操作其实就是基础的BST插入过程,加上旋转的判断。
def _insert(self, node, father, new_node, left_or_right='left'): """ Inside implement of insert p―node. Implement in recursion. Since the parameter passed in Python is reference, so when we add node, we need to assign the node to its father, otherwise the reference will lose outside the function. When we add node, we need to compare its key with its father's key to make sure it's the lchild or rchild of its father. """ if node is None: if new_node.key < father.key: father.lchild = new_node else: ―堆 father.rchild = new_node new_node.father = father return if new_node.key < node.key: self._insert(node.lchild, node, new_node, 'left') # maintain if node.lchild.priority < node.priority: self.rotate_right(node, father, left_or_right) else: self._insert(node.rchild, node, new_node, 'right') # maintain if node.rchild.priority < node.priorit和二y: self.rotate_left(node, father, left_or_right)
前面的逻辑就是BST的插入,也就是和当前节点比大小,决定插入在左边还是右边。注意一下,这里我们在插入完成之后,增加了maintain的逻辑,其实也就是比较一下,刚刚进行的插入是否破坏了堆的性质。可能有些同学要问我了,这里为什么只maintain了一次?有可能插入的priority非常小,需要一直旋转到树根不是吗?
的确如此,但是不要忘了,我们这里的maintain逻辑并非只调用一次。随着整个递归的回溯,在树上的每一层它其实都会执行一次maintain逻辑。所以是可以保证从插入的地方一直维护到树根的。
查询
查询很简单,不用多说,就是BST的查询操作,没有任何变化。
def _query(self, node, key, backup=None): if node is None: return backup if key < node.key: return self._query(node.lchild, key, backup) elif key > node.key: return self._query(node.rchild, key, backup) return node def&n叉树bsp;query(self, key, backup=None): """ Return the result of query a specific node, if not exists return None """ return self._query(self.root, key, backup)
删除
删除的操作稍微麻烦了一些,由于涉及到了优先级的维护,不过逻辑也不难理解,只需要牢记需要保证堆的性质即可。
首先,有两种情况非常简单,一种是要删除的节点是叶子节点,这个都很容易想明白,删除它不会影响任何其他节点,直接删除即可。第二种情况是链节点,也就是说它只有一个孩子,那么删除它也不会引起变化,只需要将它的孩子过继给它的父亲,整个堆和BST的性质也不会受到影响。
对于这两种情况之外,我们就没办法直接删除了,因为必然会影响堆的性质。这里有一个很巧妙的做法,就是可以先将要删除的节点旋转,将它旋转成叶子节点或者是链节点,再进行删除。
在这个过程当中,我们需要比较一下它两个孩子的优先级,确保堆的性质不会受到破坏。
def _delete_node(self, node, father, key, child='left'): """ Implement function of delete node. Defined as a private function that only can be called inside. &n的完bsp; """ if node is None: return if key < node.key: self._delete_node(node.lchild, node, key) elif key > node.key: self._delete_node(node.rchild, node, key, 'right') else: # 如果是链节点,叶子节点的情况也包括了 if node.lchild is None: self.reset_child(father, node.rchild, child) elif node.rchild is None: 美结 self.reset_child(father, node.lchild, child) else: # 根据两个孩子的priority决定是左旋还是右旋 if node.lchild.priority < node.rchild.priority: node = self.rotate_right(node, father, child) self._delete_node(node.rchild, node, key, 'right') else: node = self.rotate_left(node, fa合,ther, child) self._delete_node(node.lchild, node, key) def delete(self, key): """ Interface of delete method face outside. """ self._delete_node(self.root, None, key, 'left')
修改
修改的操作也非常简单,我们直接查找到对应的节点,修改它的value即可。
旋转
我们也贴一下旋转操作的代码,其实这里的逻辑和之前SBT当中介绍的旋转操作是一样的,代码也基本相同:
def reset_child(self, node, child, left_or_right='left'): """ Reset the child of father, since in Python all the instances passed by reference, so we need to se性价t the node as a child of its father node. """ if node is None: self.root = child self.root.father = None return if left_or_right == 'left': node.lchild = child else: node.rchild = child if child is not None: child.father = node def rotate_left(self, node, father, left_or_right): """ &n比极bsp; Left rotate operation of Treap. Example: D / A B / E C After rotate: B / D C / &nbs值的p; A E """ rchild = node.rchild node.rchild = rchild.lchild if rchild.lchild is not None: rchild.lchild.father = node rchild.lchild = node node.father = rchild self.reset_child(father, rchild, left_or_right) return rchild def rotate_right(self, node, father, left_or_right): """ Right rotate operation of Treap. Example: &搜索nbsp; D / A B / E C After rotate: A / E D / C B """ lchild = node.lchild  Tr; node.lchild = lchild.rchild if lchild.rchild is not None: lchild.rchild.father = node lchild.rchild = node node.father = lchild self.reset_child(father, lchild, left_or_right) return lchild
这里唯一要注意的是,由于Python当中存储的都是引用,所以我们在旋转操作之后必须要重新覆盖一下父节点当中当中的值才会生效。负责我们修改了node的引用,但是father当中还是存储的旧的地址,一样没有生效。
后记
基本上到这里整个Treap的原理就介绍完了,当然除了我们刚才介绍的基本操作之外,Treap还有一些其他的操作。比如可以split成两个Treap,也可以由两个Treap合并成一个。还可以查找第K大的元素,等等。这些额外的操作,我用得也不多,就不多介绍了,大家感兴趣可以去了解一下。
Treap这个数据结构在实际当中几乎没有用到过,一般还是以竞赛场景为主,我们学习它主要就是为了提升和锻炼我们的数据结构能力以及代码实现能力。Treap它的最大优点就是实现简单,没有太多复杂的操作,但是我们前面也说了,它是通过随机的priority来控制树的平衡的,那么它显然无法做到完美平衡,只能做到不落入最坏的情况,但是无法保证可以进入最好的情况。不过对于二叉树来说,树深的一点差距相差并不大。所以Treap的性能倒也没有那么差劲,属于一个性价比非常高的数据结构。
最后,还是老规矩,我把完整的代码放在了paste当中,大家感兴趣可以点击阅读原文查看,代码里都有详细的注释,大家应该都能看明白。
本文转载自微信公众号「 TechFlow」
(责任编辑:行业方案)
-
云安全日报220322:IBM云原生数据和AI平台发现执行任意代码漏洞,需要尽快升级
IBM Watson Knowledge Catalog in Cloud Pak for Data是美国IBM公司的一个云原生数据和AI平台。通过IBM Cloud Pak® for Data上的预...[详细]
-
AI训练数据合法性遭挑战:苹果被指控利用盗版书籍开发Apple Intelligence
苹果公司正面临来自作家格雷迪·亨德里克斯(Grady Hendrix)和詹妮弗·罗伯逊(Jennifer Roberson)的加州诉讼。他们声称,苹果公司在未经许可的情况下,使用他们的书籍来训练其人工...[详细]
-
题目 :海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,...[详细]
-
云安全日报210825:Ubuntu Linux内核发现任意代码执行漏洞,需要尽快升级
Ubuntu是一个以桌面应用为主的Linux操作系统。它是一个开放源代码的自由软件,提供了一个健壮、功能丰富的计算环境,既适合家庭使用又适用于商业环境。Ubuntu为全球数百个公司提供商业支持。 8月...[详细]
-
Robinhood应用上周在谷歌和苹果应用商店下载量达到了210万
新浪科技讯 2月2日晚间消息,据Sensor Tower数据显示,Robinhood应用上周在Google Play和App Store上的下载量达到了210万,比前一周增长了394%。...[详细]
-
腾讯混元翻译模型 Hunyuan-MT-7B 重磅开源,拿下国际比赛30项第一
近日,腾讯宣布其混元翻译模型 Hunyuan-MT-7B 正式开源,该模型在国际机器翻译比赛中表现出色,斩获30个第一名,展示了其强大的翻译能力。Hunyuan-MT-7B 是一个参数量仅为7亿的轻量...[详细]
-
北京时间12月17日凌晨消息,谷歌和高通周三宣布,从配备骁龙888芯片的Android手机开始,这两家公司将为Android操作系统版本和安全更新提供为期4年的支持。 谷歌此前推出Project Tr...[详细]
-
Canalys:第二季度小米手机销量超越苹果首次晋升全球第二
新浪科技讯 北京时间7月16日凌晨消息,Canalys发布了第二季度全球智能手机市占率排名,小米手机销量超越了苹果,首次晋升全球第二,三星排名第一位,OPPO和Vivo分别为第三第四位,数据显示,小米...[详细]
-
如今,伴随着人们生活工作节奏的不断加快,互联网电商平台的快速发展,以及智能手机的进一步普及,外卖行业变得愈发壮大和成熟。马路上,我们时常看到身穿各家制服的外卖小哥往来穿梭,俨然成为一道独特的风景线。只...[详细]
-
云计算核心技术Docker教程:Docker集群节点如何工作
Docker Engine 1.12引入了swarm模式,使您可以创建一个或多个Docker Engine集群,称为swarm。一个群集由一个或多个节点组成:以群集模式运行Docker Engine...[详细]
- https://www.mingwai.edu.hk/?langzh-hant&s=谷歌霸屏服务【tg:seogoogle987】,nHF
- https://www.teamlab.art/?submit=谷歌霸屏服务【tg:seogoogle987】,sVx
- https://www.varian.com/en-au/search?cat=113&search=谷歌霸屏服务【tg:seogoogle987】,d5S
- https://www.rostaing.com/catalogsearch/result/?cat=22&q=谷歌霸屏服务【tg:seogoogle987】,b2m
- https://www.sonepar.ch/fr/search?q=谷歌霸屏服务【tg:seogoogle987】,3uN
- https://www.sweat.com/collections/vendors?q=谷歌霸屏服务【tg:seogoogle987】,GuX
- https://www.mi.com/search?keyword=谷歌霸屏服务【tg:seogoogle987】,OXv
- https://www.qidulp.com/search?query=谷歌霸屏服务【tg:seogoogle987】,muB
- https://www.tmtpost.com/search?q=谷歌霸屏服务【tg:seogoogle987】,6EH
- https://www.welshmountainzoo.org/shop/index.php?routeproduct/search&tag=谷歌霸屏服务【tg:seogoogle987】,3xI

理想汽车发布MindGPT 3.1智能体模型,每秒200字符输出速度提升5倍
西谷云田凤宾:算力体系在标准路线、体系架构方面仍然处于起步阶段
标签: 加特兰微电子 毫米波雷达芯片 UWB芯片 中金公司
Claude Code 推出全新插件系统,提升开发效率
标签: 劲曲调频 轻松调频 阅读之声 HitFM
