The heap is a classical data structure that puts a complete binary (or d-ary for the generalized version) tree into a contiguous array, storing the elements in breadth-first traversal order. In this way, all elements from the same level of the tree are stored contiguous one after the other.
I'm implementing a data structure which, under the hood, is a complete balanced tree of fixed degree d, and I want to store the tree in a contiguous form to free the space of node pointers. So I thought of putting the nodes into the breadth-first order used in heaps, but then I'm worried about cache performance of a typical search from the root down to a leaf, since at each level l, I jump over a lot of elements.
Is there a way to obtain compact contiguous representation of a d-ary complete tree, based on depth-first order instead?
This way, the nodes touched during a search of a leaf seem to me more likely to be found closer to each other. The problem then is how to retrieve the index of the parent and children of a node, but also I'm wondering which operations on the tree are in general efficient in this setting.
I'm implementing this thing in C++, in case it matters at all.
left-child(i) = i + 1
, and with a bit more thought,right-child(i) = i + d^(level(i) - MAX_LEVEL)
. How to get the current level fromi
I couldn't figure out in a few minutes. I suspect it involved a logarithm. – user395760