简体   繁体   English

在不使用父指针的情况下在红黑树中查找等级

[英]Finding the rank in a red-black tree without using a parent pointer

I was given code for a red-black tree in class. 课堂上给了我一棵红黑树的代码。 The struct used to create a node does not have a parent pointer. 用于创建节点的结构没有父指针。 I have most of my project working, but I cannot figure out how to compute the rank in O(lg n) time. 我的大部分项目都在工作,但我不知道如何计算O(lg n)时间的排名。 By rank, I mean if you were to do an inorder-traversal and save the keys to an array starting at index 1, what index the given key would be stored. 按等级,我的意思是,如果要进行有序遍历并将键保存到从索引1开始的数组中,则给定键将存储在哪个索引中。 Doing this would be in O(n) time though which is not allowed. 这样做是在O(n)时间内完成的,尽管这是不允许的。

Reading through CLRS, the chapter Augmenting Data Structures has code to return the rank given the key. 通过阅读CLRS,“增强数据结构”一章中的代码可以返回给定键的等级。 This is exactly what I need, but the problem is the code uses a parent pointer. 这正是我所需要的,但是问题是代码使用了父指针。 Since we never used parent pointers in any of our red-black tree examples and this code does not include a parent pointer, I don't believe we are to change the entire given code just to get the rank to work, which leads me to believe there is a way to do it without using a parent pointer. 由于我们在任何红黑树示例中都从未使用过父指针,并且此代码不包含父指针,因此我不相信我们要更改整个给定代码只是为了使排名起作用,这导致我相信有一种方法可以不用父指针。

The (fields?) that exist in the node struct are: a key (int), a pointer to the left child, pointer to the right child, sub-tree size (int), and the color (int). 节点结构中存在的(字段?)是:键(int),指向左子代的指针,指向右子代的指针,子树大小(int)和颜色(int)。

All code is done in C. What I am looking for is if this is possible, and how I might accomplish this with or without source code (a good explanation would be perfect). 所有代码都是用C语言完成的。我所寻找的是,如果可能的话,以及无论有没有源代码,我如何实现这一点(一个很好的解释将是完美的)。

Assumption: sub-tree size includes root node of sub-tree. 假设:子树的大小包括子树的根节点。 Call the value to be ordered in a. 在中调用要排序的值。

Then, this algorithms gets you the rank in O(lgn): 然后,此算法将使您获得O(lgn)的排名:

1: let rank=subtree size(root of tree)
2: if you go left:
- adjust rank=rank - (subtree size(sts) of right child (rc) of root) - 1
- move to left child(lc) of root
3: if you go right:
- adjust rank=rank(prior)
- move to rc(root)
4: iterate 2-3 (replacing root with current node) until you are at the node with value a
5: if this node has a rc, adjust a final time
- rank = rank - (sts(rc))

Done. 做完了

Note: assumes the usual left-to-right lower-to-higher ordering of rb tree. 注意:假定rb树的排列顺序是从左到右,从低到高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM