搜索RB树中的特定节点

seach for a specific node in an RB-tree

本文关键字:节点 RB 搜索      更新时间:2023-10-16

假设我有一个RB树,由与人们年龄相对应的数字组成;并且假设每个节点也有一个性别(女性或男性)。

我的问题是,如何使用OS-SELECT和秩值从树中获得特定的数字?具体数字意味着,在树上找到第二年轻的人。

示例:OS-SELECT(root,2)返回树中第二年轻的人。

目的不仅仅是找到第二个或第三个yougest节点,目的是找到第二小的男性或第二小的女性

只需按顺序遍历树并计算满足谓词的元素。在这种情况下,谓语应该是"is male"。在二进制搜索树中找到一个元素可以让我们提前结束遍历,这对实现来说不一定是微不足道的,所以这里有一个简单的算法伪代码:

# return value is used to track how many matching nodes must be
# found until the k'th one is reached
int OS-SELECT(node, rank)
  if not node        # leaf reached?
    return rank      # Keep searching.
  rank = OS-SELECT(node.left, rank)
  if not rank        # Node was found in left subtree.
    return 0         # End early.
  if predicate(node) # Test the predicate.
    if not --rank    # The node matches: There are less matches to go through.
      visit(node)    # Rank dropped to 0: Found it. Visit the node and
      return 0       # end early.
  return OS-SELECT(node.right, rank)