def top_clusters(tree, k):
 def item(node):
  return ((node.is_leaf, (- node.value.height)), node)
 heap = [item(tree)]
 while (len(heap) < k):
  (_, cl) = heap[0]
  if cl.is_leaf:
   assert all((n.is_leaf for (_, n) in heap))
   break
  (key, cl) = heapq.heappop(heap)
  (left, right) = (cl.left, cl.right)
  heapq.heappush(heap, item(left))
  heapq.heappush(heap, item(right))
 return [n for (_, n) in heap]

def top_clusters ( tree , k ) : def item ( node ) : return ( ( node . is_leaf , ( - node . value . height ) ) , node ) heap = [ item ( tree ) ] while ( len ( heap ) < k ) : ( _ , cl ) = heap [ 0 ] if cl . is_leaf : assert all ( ( n . is_leaf for ( _ , n ) in heap ) ) break ( key , cl ) = heapq . heappop ( heap ) ( left , right ) = ( cl . left , cl . right ) heapq . heappush ( heap , item ( left ) ) heapq . heappush ( heap , item ( right ) ) return [ n for ( _ , n ) in heap ]
return k topmost clusters from hierarchical clustering .