www.delorie.com/gnu/docs/avl/libavl_72.html | search |
Buy GNU books! | |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Converting the vine, once we have it, into a balanced tree is the interesting and clever part of the balancing operation. However, at first it may be somewhat less than obvious how this is actually done. We will tackle the subject by presenting an example, then the generalized form.
Suppose we have a vine, as above, with 2**n - 1 nodes for positive integer n. For the sake of example, take n = 4, corresponding to a tree with 15 nodes. We convert this vine into a balanced tree by performing three successive compression (see compression) operations.
To perform the first compression, move down the vine, starting at the root. Conceptually assign each node a "color", alternating between red and black and starting with red at the root.(6) Then, take each red node, except the bottommost, and remove it from the vine, making it the child of its black former child node.
After this transformation, we have something that looks a little more like a tree. Instead of a 15-node vine, we have a 7-node black vine with a 7-node red vine as its right children and a single red node as its left child. Graphically, this first compression step on a 15-node vine looks like this:
To perform the second compression, recolor all the red nodes to white, then change the color of alternate black nodes to red, starting at the root. As before, extract each red node, except the bottommost, and reattach it as the child of its black former child node. Attach each black node's right subtree as the left subtree of the corresponding red node. Thus, we have the following:
The third compression is the same as the first two. Nodes 12 and 4 are recolored red, then node 12 is removed and reattached as the right child of its black former child node 8, receiving node 8's right subtree as its left subtree:
The result is a fully balanced tree.
5.12.2.1 General Trees 5.12.2.2 Implementation 5.12.2.3 Implementing Compression
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
webmaster | delorie software privacy |
Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |