二进制搜索树的数组实现

Array implementation of Binary Search Tree

本文关键字:实现 数组 搜索树 二进制      更新时间:2023-10-16

我正在使用1D数组创建二进制搜索树。我的问题是插入功能。

插入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;
    }

您将当前节点保持在两个不同的变量中:将节点的指针保留在temp中,并且节点的索引保留在i中。这本身(尽管可能不是最佳)本身并不是问题。但是,您不会使两个变量保持一致(您对指针的更新方式与索引不同)。一个简单的修复是使这一一致:

temp = &ptr->arr[i*2]; //the pointer update is correct
i = i * 2; //same update as above
//...
temp = &ptr->arr[i*2+1];
i = i * 2 + 1; //same update as above

我认为,最好完全放下指针temp,并始终通过其索引访问数组。这不需要两个变量之间的任何同步。