While trying to understand binary (search) trees, I stumbled upon the question of whether a BST can be stored in a flat array efficiently (i.e., without wasting space). After google'ing and searching in forums (including SO), I didn't find anything that satisfied me. Most people want to store BTs (l=2*i+1, r=2*i+2) or accept the fact that empty children of a node are represented as nil values (and stored like that, unnecessarily eating space).
So I wrote my own algorithm, harnessing the fact that child nodes in BSTs have a particular ordering property (smaller than root: left, larger than root: right).
To store a BST, I just linearly write it to an array, depth-first. That happens in O(n), recursing into the tree's child nodes. The array is then exactly n entries long, n being the number of nodes in the BST.
To reconstruct the BST from the array, I follow two rules when encountering a new entry in the array:
The next left node (if existing) is the next smaller than the current one.
The next right node (if existing) is the next one ...
- ... bigger than the current one
- ... no larger than the smallest parent key when last branching
left - ... smaller than parent if in parent's
leftbranch
This also happens in O(n).
This works surprisingly well for very, very large trees of random structure (as long as they are BSTs). Empirical tests have never shown any problems. I made a working code example in C++ here, the two conversion functions being toArray and fromArray.
Now to my question: Does this generalize? I am afraid to oversee crucial problems with this. The fact that I haven't found anything else on that on the net makes me wonder whether
a) I'm too stupid to find it,
b) It's common sense and nobody talks about it or
c) It's plain wrong.
I'd be very grateful for anybody that is proficient on the topic to enlighten me on this.
Thanks a lot already.
EDIT:
After google'ing some more and completely ignoring the array detail, I found a couple of valid solutions. The most prominent one (as explained here and here) was to store the BST using pre-order traversal.