【发布时间】:2017-12-06 18:29:00
【问题描述】:
我正在使用一维数组创建二叉搜索树。我的问题在于插入功能。
当我输出树时,插入 5、8、3、1、4 和 9 会产生正确的索引。但是,当我尝试将 9 之后的数字添加到树中时,索引不正确。例如前面提到的数字,9 的索引是 7。如果我插入 17,它应该是 9 的右孩子,而不是它的索引 15,它的索引是 11。
我知道问题在于我如何增加 i,但我不确定如何解决它。任何帮助表示赞赏。谢谢!
void insert(int x)
{
int i = 1; //Counter
if (ptr->arr[1] == -1) //If bst is empty.
{
ptr->arr[1] = x;
}
else
{
int *temp = &ptr->arr[1]; //Temp starts at root
int *parent = NULL;
while (*temp != -1 && *temp != x)
{
if (x < *temp)
{
parent = temp;
temp = &ptr->arr[i*2];
i++;
}
else
{
parent = temp;
temp = &ptr->arr[i*2+1];
i+=2;
}
}
*temp = x;
}
【问题讨论】:
标签: c++ arrays binary-search-tree