Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Binary Heap be a binary tree or linked list?

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;
}
like image 872
Yunus Eren Güzel Avatar asked Aug 02 '26 06:08

Yunus Eren Güzel


1 Answers

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
like image 105
2 revs, 2 users 98%bummi Avatar answered Aug 04 '26 04:08

2 revs, 2 users 98%bummi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!