Implementing an AVL tree

The AVLTree class

•      Two data fields

–   Entry root

–   Int size

 

The Entry class

•      Five data fields

–   Object element;

–   char balanceFactor = ‘=‘;

•   Initialized to ‘=‘

•   The possible values are =, R, and L

•   If the node has the same number of children, it should be =

•   If the right subtree is one longer than the left it should be R

•   If the left subtree is one longer than the right it should be L

–   Three reference variables pointing to Entry nodes

•   Left, right, parent

 

The add method

•      We use top town  design here, by letting add call other methods to do some of the work

•      We use two local variables

–    Entry temp = root, ancestor = null

–    Temp will point to the node which is the parent of the added node

–    Ancestor

 

•      First,  is the root null?

•      Then, if not, should we go right or left

 

•      When we find the place to enter the node, we put it in, then  fix it in case it made the tree unbalanced. 

–    We call fixAfterInsertion to fix it

•      Then we adjust size, and return true, if it was not a duplicate element.

 

The fixAfterInsertion method

•      It takes two arguments, both type Entry

•      Six cases

–    Case 1: all ancestors of inserted have balanceFactor of '='

–    Case 2: insertion in opposite subtree of ancestor's balanceFactor

–    Case 3: ancestor's balanceFactor = 'R' and  o > ancestor's right element

–    Case 4: ancestor's balanceFactor = 'L' and  o < ancestor's left element

–    Case 5: ancestor's balanceFactor = 'L' and  o > ancestor's left element

–    Case 6: ancestor’ balanceFactor  = 'R' and  o < ancestor.right.element