鉴于以下问题:
“存储数字流中最大的 5000 个数字”
想到的解决方案是二叉搜索树,它维护树中节点数的计数,并在计数达到 5000 时引用最小节点。当计数达到 5000 时,可以将要添加的每个新数字与树中最小的项目。如果更大,则可以添加新数字,然后删除最小的数字并计算新的最小数字(这应该很简单,已经有了以前的最小数字)。
我对这个解决方案的担忧是二叉树自然会偏斜(因为我只删除一侧)。
有没有办法解决这个问题,不会产生一个非常倾斜的树?
如果有人想要它,到目前为止,我已经为我的解决方案包含了伪代码:
process(number)
{
  if (count == 5000 && number > smallest.Value)
  {
    addNode( root, number)
    smallest = deleteNodeAndGetNewSmallest ( root, smallest)
  }
}
deleteNodeAndGetNewSmallest( lastSmallest)
{
  if ( lastSmallest has parent)
  {
    if ( lastSmallest has right child)
    {
      smallest = getMin(lastSmallest.right)
      lastSmallest.parent.right = lastSmallest.right
    }
    else
    {
      smallest = lastSmallest.parent
    }
  }
  else 
  {
    smallest = getMin(lastSmallest.right)
    root = lastSmallest.right
  }
  count--
  return smallest
}
getMin( node)
{
  if (node has left)
    return getMin(node.left)
  else
    return node
}
add(number)
{
  //standard implementation of add for BST
  count++
}