I have a set of items that are supposed to for a balanced binary tree. Each item is of the form (data,parent), data being the useful information and parent being the index of the parent node in the binary tree.
Nodes in the tree are numbered left-to-right, row-by-row, like this:
1
___/ \___
/ \
2 3
_/\_ _/\_
4 5 6 7
These elements come stored in a linked list. How should I order this list such that it’s easier for me to build the tree? Each parent node will be referenced (by index) by exactly two child nodes; if I sort these by parent index, the sorting must be stable.
You can sort the list in any stable sort, according to the
parentfield, in increasing order.The result will be a list like that:
Note that in this list, since we used a stable sort – for each two pairs
(d_i,x), (d_i+1,x)in the sorted list,d_iis the left leaf!Now, you can populate the tree in breadth-first traversal,
Since it is homework – I still want you to make sure you understand everything by your own. So I do not want to “feed answer”. If you have any specific question, please comment – and I will try to edit and explain the relevant parts with more details.
Bonus: The result of this organization is very common way to implement a binary heap structure, which is a complete binary tree, but for performance, we usually store it as an array, which is very similar to the output generated by this approach.