I noticed the following comment on the AVL Tree Wikipedia page :
"If each node additionally writes the size of its subtree (including its and its descendants), then the nodes can be restored by an index in O (log n)."
I have google and I found several places that mentioned access by index , but can't seem to find an explanation for the algorithm to write.
Many thanks
[UPDATE] Thanks to the people. If @templatetypedef is found, the answer is in conjunction with one of the @ user448810 links to especially help. Especially this snip:
βThe key to both of these functions is that the node index is the size of its left child. While we are dropping the tree through its left child, we just take the node index. But when we need to move down the tree through its right child, we have to adjust the size to include half the tree we excluded. "
Since my implementation is immutable, I did not need to do any additional work when rebalancing, since each node calculates its size during construction (just like the implied scheme)
My final implementation has ended:
class Node<K,V> implements AVLTree<K,V> { ... public V index(int i) { if (left.size() == i) return value; if (i < left.size()) return left.index(i); return right.index(i - left.size() - 1); } } class Empty<K,V> implements AVLTree<K,V> { ... public V index(int i) { throw new IndexOutOfBoundsException();} }
Which is slightly different from other implementations, let me know if you think I have a bug!
source share