【问题标题】:Array implementation of Binary Search Tree二叉搜索树的数组实现
【发布时间】: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


    【解决方案1】:

    您在两个不同的变量中维护当前节点:指向节点的指针保存在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 并始终通过其索引访问数组也是一个好主意。这不需要两个变量之间的任何同步。

    【讨论】:

    • 谢谢。我尝试了您在上面所做的其他更改,但出现运行时错误。我认为降低温度是要走的路。
    • 那么你的数组可能不够大。
    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2010-11-22
    • 2013-05-03
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多