AVL树插入
当我递归调用插入函数以将节点添加到 AVL 树时,如何计算特定节点的平衡因子。我还没有开始研究轮换逻辑。我只是想计算平衡因子。
在我当前的尝试中,我被迫存储左和右的高度。正确的子树,因为没有它们我找不到平衡因子。
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) );
}
...
}
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) );
}
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
平衡因子是节点的右子树和左子树之间的高度差。
创建新节点时,将平衡因子初始化为零,因为它是平衡的(它没有子树)。
如果要在右侧插入新节点,请将平衡因子增加 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.
这是一个非常简单的方法。如果有递归
height()
函数,则平衡因子可以简单地计算为:但这不是最好的方法,因为这种方法的复杂性是
O( h )
其中h
是AVL树中节点
的高度。为了更好的方法,需要进行更广泛的讨论:)网络上有许多关于 AVL 树的资源,选择的一些是:
顺便说一句,
avlAdd()< /code> 函数看起来错误。我不知道
aNew->num
与a->num
相比在哪里。是否转到左子树或右子树必须取决于此。给定的代码似乎无条件添加到左子树。Here is a very simple approach. If there was a recursive
height()
function, then balance factor can be computed simply asThis is not the best approach though, since the complexity of this approach is
O( h )
whereh
is the height of thenode
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:
BTW, The
avlAdd()
function looks wrong. I don't see whereaNew->num
is compared toa->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.