Global Feed Post Login
Replying to Avatar jb55

trees can be scary to programmers: lots of pointers flying around everywhere to different parts of memory, lots of memory allocations, but fixed and balanced trees have a very simple representation that you can store and navigate in a straight line (programmers like straight lines, we call them arrays)

The numbers in this image are the index into an array. Given any position in the tree, you can find a parent or sibling element with a few arithmetic operations which result in another index.

No allocating complex data structures, no chasing pointers around, just a bit of math to jump around a tree flattened into a straight line. As a programmer finding elegant solutions like this is a pure dopamine hit. Code can be beautiful 🥹

#nerdstr #treestr

Avatar
edo 1y ago

I agree with the elegance. This is how heaps are stored in arrays: https://en.m.wikipedia.org/wiki/Heap_(data_structure)

Reply to this note

Please Login to reply.

Discussion

Avatar
jb55 1y ago

Also the sibling calculation is super simple:

sibling = ind + ((ind & 1) ? 1 : -1)

Thread collapsed