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.
开发者_如何学PythonIn 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) );
}
...
}
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.
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:
- http://en.wikipedia.org/wiki/AVL_tree
- C implementation: http://www.stanford.edu/~blp/avl/libavl.html
- Animation: http://www.cs.jhu.edu/~goodrich/dsa/trees/avltree.html
- 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.
精彩评论