In the previous post we defined the tree itself and the methods to add and delete a child. This post covers the pack and re-index functionality, this allows the removal of unused space and makes the tree more compact. The pack could be very useful to make the tree easier to load in the cpu cache.
Note that the first post was updated due to the introduction of the new method.
Before starting writing some code let’s see what is the goal of the new method on an example. Let’s say that we a tree with a root and three nodes. We called delete on index 2 child, and pack after:
As you can see from above the node index 2 is moved to index 3 and the node at index 1 is updated with the new index, moreover the last value is dropped from the memory chunk because is not needed anymore.
Note that the allocated space is not dropped, if we want to add a new node we will not pay the allocation cost associated to the memory chunk allocation.
The pack method will move all the deleted nodes at the end of the memory chunk and pack all the valid nodes near the start. Before introducing the method itself, however, we want to write some helpers to:
retrieve the first deleted node starting from the head of the memory chunk;
retrieve the first non deleted node starting from the end;
update two swapped nodes.
Using the previous methods we can write the pack one, as you can see the implementation is fairly simple compared to the add and delete child:
Note that we need to save and return all the new indices because we physically moved some nodes. If the result is empty the tree was already packed.