Often we need trees in algorithms and I get out a tree with lots of pointers and recursion.
Sometimes I need more speed an I put the tree into an 2D array like so:
A binary tree can be stored in an array more efficiently as explained here: http://en.wikipedia.org/wiki/Binary_tree#Arrays:
From Wikipedia:
In this compact arrangement, if a node has an index
i
, its children are found at indices(2i + 1)
(for the left child) and(2i + 2)
(for the right), while its parent (if any) is found at indexfloor((i-1)/2)
(assuming the root has index zero).This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it is expensive to grow and wastes space proportional to
(2H - n)
for a tree of heightH
withn
nodes.
In other words, it will waste space if your tree is not a complete binary tree, but it will still be a bit more compact than a plain 2D array.