Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Inserting Items into an AVL Tree

Inserting an item into an AVL tree is a two-part process. First, the item is inserted into the tree using the usual method for insertion in binary search trees. After the item has been inserted, it is necessary to check that the resulting tree is still AVL balanced and to balance the tree when it is not.

Just as in a regular binary search tree, items are inserted into AVL trees by attaching them to the leaves. To find the correct leaf we pretend that the item is already in the tree and follow the path taken by the find method to determine where the item should go. Assuming that the item is not already in the tree, the search is unsuccessful and terminates an an external, empty node. The item to be inserted is placed in that external node.

Inserting an item in a given external node affects potentially the heights of all of the nodes along the access path  , i.e., the path from the root to that node. Of course, when an item is inserted in a tree, the height of the tree may increase by one. Therefore, to ensure that it resulting tree is still AVL balanced, the heights of all the nodes along the access path must be recomputed and the AVL balance condition must be checked.

Sometimes increasing the height of a subtree does not violate the AVL balance condition. For example, consider an AVL tree tex2html_wrap_inline62666. Let tex2html_wrap_inline63750 and tex2html_wrap_inline63754 be the heights of tex2html_wrap_inline62662 and tex2html_wrap_inline62664, respectively. Since T is an AVL tree, then tex2html_wrap_inline63848. Now, suppose that tex2html_wrap_inline63850. Then, if we insert an item into tex2html_wrap_inline62664, its height may increase by one to tex2html_wrap_inline63854. The resulting tree is still AVL balanced since tex2html_wrap_inline63856. In fact, this particular insertion actually makes the tree more balanced! Similarly if tex2html_wrap_inline63858 initially, an insertion in either subtree will not result in a violation of the balance condition at the root of T.

On the other hand, if tex2html_wrap_inline63850 and an the insertion of an item into the left subtree tex2html_wrap_inline62662 increases the height of that tree to tex2html_wrap_inline63866, the AVL balance condition is no longer satisfied because tex2html_wrap_inline63868. Therefore it is necessary to change the structure of the tree to bring it back into balance.




next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.