Consider a binary heap, with n elements. Only the shape is important; the sorting property doesn't matter here. I'm trying to figure out the offset of the root element in an in-order traversal. Thus, if the heap had size 10, the tree would look like:
O
/ \ .
O O
/ \ / \ .
O O O O
/\ /
O O O
Moreover, the tree (with nodes replaced by their offsets in an in-order traversal) would look like:
6
/ \ .
3 8
/ \ / \ .
1 5 7 9
/\ /
0 2 4
...and the root element would have offset 6. How can I figure this out? I have a horrible-looking O(1) algorithm which I haven't tested and which requires the next-power-of-two operation, and of course a naive O(n) implementation. Does anyone know of a simpler way to figure this out?