tags:

views:

50

answers:

2

How do I calculate the balance factor for a particular node, when I am recursively calling an insert function for adding a node to an AVL tree. I haven't started on the rotation logic. I simply want to calculate the balance factors.

In my current attempt, I am forced to store heights of left & right subtrees as I can't find the balance factor without them.

typedef struct _avlTree
{
 int num;
 int balFactor;
 int height[2];  // left & right subtree heights
 struct _avlTree *left,*right;
} *avlTree;


int avlAdd(avlTree a,avlTree aNew)
{
                ...
  if(a->left == NULL)   // left subtree insertion case
  {
   a->left = aNew;
   return(1); 
  }
  else
  {
   a->height[0] = avlAdd(a->left,aNew);
   a->balFactor = a->height[0] - a->height[1];
   return( (a->height[0]>a->height[1]) ? (a->height[0]+1) : (a->height[1]+1) );
  }
                ...
}
A: 

The balance factor is the difference in heights between the right and left subtrees of a node.

When creating a new node, initialize the balance factor to zero since it is balanced (it has no subtrees).

If you are inserting a new node to the right, increase the balance factor by 1.

If you are inserting a new node to the left, decrease the balance factor by 1.

After rebalancing (rotating), if you increase the height of the subtree at this node, recursively propagate the height increase to the parent node.

Doug Currie
what about the ancestors of the immediate parent node? how do I change their balance factor?
xyz
When you recursively descend to the subtree, you will know whether you are descending to the right or to the left. The recursive call should return 0 if the subtree height is not changed, and 1 if the height is increased. Add this value to the appropriate balance factor (depending on which side you descended), and continue rebalancing.
Doug Currie
A: 

Here is a very simple approach. If there was a recursive height() function, then balance factor can be computed simply as

node->balFactor = height( node->right ) - height( node->left );

This is not the best approach though, since the complexity of this approach is O( h ) where h is the height of the node in the AVL tree. For better approach, a bigger discussion is required :)

There are numerous resources on AVL tree in the web, a chosen few are:

  1. http://en.wikipedia.org/wiki/AVL_tree
  2. C implementation: http://www.stanford.edu/~blp/avl/libavl.html
  3. Animation: http://www.cs.jhu.edu/~goodrich/dsa/trees/avltree.html
  4. Animation: http://www.strille.net/works/media_technology_projects/avl-tree_2001/

BTW, The avlAdd() function looks wrong. I don't see where aNew->num is compared to a->num. Whether to go to left subtree or right subtree must depend on that. The given code seems to be adding to the left subtree unconditionally.

ArunSaha