-2

Suppose I have a RB-tree consisting of numbers which correspond to people's age; and suppose each node also have a gender (female or male).

My question is, how to get a specific number from that tree using OS-SELECT and rank value? Specific number means, find 2nd youngest man in the tree.

Example: OS-SELECT(root, 2) which returns second youngest man of the tree.

The aim is not just finding the 2nd or third yougest node, the aim is to find 2nd youngest men or 2nd youngest women

thinwater
  • 11
  • 2
  • Sorry, for closing. I intended to vote, but not close single handedly (I didn't realize I had gained such power). Given your elaboration, this does not seem an exact duplicate. – eerorika Dec 28 '15 at 15:39

1 Answers1

0

Simply traverse the tree in-order and count the elements that satisfy the predicate. In this case the predicate would be "is male". Finding an element in a binary search tree allows us to end traversal early, which is not necessarily trivial to implement, so here is a simple pseudocode for the algorithm:

# 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)
eerorika
  • 232,697
  • 12
  • 197
  • 326