I am struggling to write a recursive algorithm to extract the max(root) from a max heap. The heap is constructed as a tree. I know that I should swap the last node with the root and push it down recursively. But there is no pseudocode on the internet or stack overflow to deal with trees. The extract algorithms that I have seen are based on arrays.
So let's say that I find the right most leaf.
Is there any solution that you can suggest?
void find_last(heap_node* root,int level,int* last_level,bool isRight,heap_node** res){
if(root == NULL)
return;
if(isRight && !root->left && !root->right && level > *last_level){
*res = root;
*last_level = level;
return;
}
find_last(root->right,level+1,last_level,true,res);
find_last(root->left,level+1,last_level,false,res);
}
And i made a function call like this
heap_node* last = NULL;
int last_level = -1;
find_last(root,0,&last_level,false,&last);
That is the code of finding the deepest right node. And it is not working :D
Efficiently finding the last node in a heap that's implemented as a tree requires that you maintain a count of nodes. That is, you know how many items are in the heap.
If you know how many items are in the heap, then you get the binary representation of the number and use that to trace through the tree to the last node. Let me give you an example. You have this heap:
1
/ \
2 3
/ \ / \
4 5 6
There are 6 items in the heap. The binary representation is 110
.
Now, moving from right to left in the binary representation. You remove the first '1' and you're at the root node. The rule is that you go right if the digit is '1', and left if the digit is '0'. At the root node, you have 10
. So you go right and remove that digit, leaving you with 0
. You're at the node marked "3". The remaining digit is 0
, so you go left. That puts you at the last node in the heap.
The algorithm for sifting down through the heap is the same regardless of whether the heap is represented as an array or as a tree. The actual steps you take to swap nodes is different, of course. When swapping nodes, you have to be careful to set the child pointers correctly. One place people often forget is when swapping the root node with the last node.
My suggestion is that you code this up and then single-step in the debugger to make sure that you have the pointer assignments right.