您的位置:首页 > 其它

非递归实现的bst的根插入操作

2014-05-26 10:18 232 查看
/*非递归实现的bst的根插入操作

使用数组的栈实现,在旋转的时候要注意改变节点的指向,这个很关键

*/

typedefstruct
stackNode *STACK,NSTACK;
struct stackNode
{
PBSTNode parent;
};
STACK g_stack;
int g_index;
void BSTSstack(int max)
{
g_stack =
malloc(sizeof(&g_stack)*max);
if (!g_stack)
{

printf("g_stack is failed");
return;
}
memset(g_stack,0,sizeof(&g_stack)*max);
g_index =
0;
}

void BSTinsertF(Item item)
{
if (header ==z)
{
header =
NEW(item,z,
z, 1);
return;
}
PBSTNode p =
header,x = p;

Key v =
key(item);
while (x !=
z)
{
p = x;
if (v <
key(x->data))
{
g_stack[g_index].parent = p;
g_index +=1;
x = x->left;
if (x ==
z)
{
p->left =NEW(item,z,z,
1);
}
}
else
{
g_stack[g_index].parent = p;
g_index +=1;
x = x->right;
if (x ==
z)
{
p->right =NEW(item,z,z,
1);
}
}

}
PBSTNode link =
NULL;
int i =
g_index -1;
for (;i >=
0;--i)
{
link =g_stack[i].parent;
if (v <
key(link->data))
{
link =rotR(link);
if (i-1 >=
0)
{
g_stack[i -
1].parent->right = link;
}
}
else
{
link =rotL(link);
if (i-1 >=
0)
{
g_stack[i -
1].parent->left = link;
}

}
}
for (i =
g_index-1;i >=0; --i)
{
g_stack[i].parent =NULL;
}
g_index =
0;
header = link;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: