From e002340e508af36e50615182785130a6320b08e8 Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Tue, 13 May 2014 13:35:02 +0400 Subject: [PATCH] heap: fix `heap_remove()` Remove should shuffle items in both directions, not just down. It is required, because `max` node could be not the actual maximum value in the tree. fix #1267 Signed-off-by: Fedor Indutny --- src/heap-inl.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/heap-inl.h b/src/heap-inl.h index 907abe65..1e2ed60e 100644 --- a/src/heap-inl.h +++ b/src/heap-inl.h @@ -227,6 +227,13 @@ HEAP_EXPORT(void heap_remove(struct heap* heap, break; heap_node_swap(heap, child, smallest); } + + /* Walk up the subtree and check that each parent is less than the node + * this is required, because `max` node is not guaranteed to be the + * actual maximum in tree + */ + while (child->parent != NULL && less_than(child, child->parent)) + heap_node_swap(heap, child->parent, child); } HEAP_EXPORT(void heap_dequeue(struct heap* heap, heap_compare_fn less_than)) {