I have an assignment to implement a binary heap. However, I'm not sure whether I should implement the binary heap as a binary tree data structure or a simple double linked list.
If I should implement as a binary tree, how should I keep track of the last element of the tree in order to insert a new element? In linked list that would be much easier.
So, does binary heap have to be a binary tree? If yes, how to track the last element?
Note: In my assignment there is a statement like this: But you will implement the binary heap not as an array, but as a tree.
To be more clear this is my node:
struct Word{
char * word;
int count;
struct Word * parent;
struct Word * left_child;
struct Word * right_child;
}
Solution taken from the question.
by @Yunus Eren Güzel
SOLVED:
After five hours of study I have found a way to implement heap as a pointer based tree. The insertion algorithm is :
insert
node = create_a_node
parent = get_the_last_parent
node->parent = parent
if parent->left==NULL
parent->left=node
else
parent->right=node
end insert
get_last_parent parent,&height
height++
if parent->left==NULL || parent->right==NULL
return parent;
else
int left_height=0,right_height=0;
left = get_last_parent(parent->left,&left_height)
right = get_last_parent(parent->right,&right_height)
if left_height == right_height
height += right_height
return right
else if left_height > right_height
height += left_height
return left
end get_last_parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With