搜索RB树中的特定节点

时间:2015-12-28 15:18:57

标签: c++ binary-search-tree red-black-tree

假设我有一个RB树,其中包含符合人们年龄的数字;并假设每个节点也有性别(女性或男性)。

我的问题是,如何使用OS-SELECT和排名值从该树中获取特定数字?具体数字意味着,找到树中第二个最年轻的人。

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

目的不仅仅是找到第二个或第三个最佳节点,目的是找到第二个最年轻的男性或第二个最年轻的女性

1 个答案:

答案 0 :(得分:0)

只需按顺序遍历树,并计算满足谓词的元素。在这种情况下,谓词将是"是男性"。在二叉搜索树中查找元素允许我们尽早结束遍历,这对于实现来说不一定是微不足道的,所以这里有一个简单的算法伪代码:

# 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)