next up previous index
Next: Priority Queues Up: Array Representation Previous: Array Representation   Index


Arithmetic of Tree Traversal

An important benefit of the array representation is that we can move around the tree, from parent to children or from child to parent, by simple arithmetic. In general

where division, to obtain the parent, returns the integer part. Of course node $i$ may not have any children, or it may only have one child. Suppose there are $n$ nodes in the tree. Then node $i$ has a left child if $2i+1 < n$ and a right child if $2i+2 < n$. Conversely, node $i$ has a parent if $i > 0$, otherwise it is the root.

You should note that some authors leave the first element of the array empty, so that the data items are stored in elements $1, \ldots, n$. The children are then at $2i$ and $2i+1$ and the parent is at $i/2$. This might make for slightly more efficient code, but overall our coding will be simpler if we load the array from $0$.


next up previous index
Next: Priority Queues Up: Array Representation Previous: Array Representation   Index
Peter Williams 2005-06-07