【问题标题】:Why won't this insert function update my binary search tree?为什么这个插入函数不会更新我的二叉搜索树?
【发布时间】:2017-09-11 18:46:32
【问题描述】:

我基本上是想在我的树中插入一个数字。最初我传递命令 insert(root, 10),然后我的函数递归遍历树以插入值。遍历工作正常,但我的树不会更新。我已经通过我的构造函数在这个类中构建了一棵树。我的树在插入函数之前的中序遍历是{0, 1, 2, 3, 4, 5, 6, 7 ,8, 9},插入之后也是如此

我的插入函数:

private: 

node* root

void insert(node* ptr, int num) {
            if (ptr == NULL) {
                    ptr = new node;
                    ptr->data = num;
                    ptr->left = NULL;
                    ptr->right = NULL;
                    return;
            }

            else if (ptr->data >= num) {
                    insert(ptr->left, num);
            }

            else if (ptr->data < num) {
                    insert(ptr->right, num);
            }
    }

创建初始树的班级的私人成员

node* createTree(int array[], int start, int end) {

            if(start > end) {
                    return NULL;
            }

            int mid;
            node* newNode = new node;

            if (((start + end) % 2) != 0) {
                    mid = ((start + end) / 2) + 1;
            }

            else {
                    mid = (start + end) / 2;
            }      

            newNode->data = array[mid];
            newNode->left = createTree(array, start, mid - 1);
            newNode->right = createTree(array, mid + 1, end);

            cout << newNode->data << " " << newNode << endl;

            return newNode;
    }

构造函数

BST(int array[], int length) {
            root = createTree(array, 0, length - 1);
    }

【问题讨论】:

  • 显示node 的声明会有所帮助。见minimal reproducible example
  • 如果ptrnullptr,您将分配一个新的node,然后由于insert 返回后新的node 无法访问而导致内存泄漏。
  • 那么我应该如何解决这个问题?我是编码和这个网站的新手。我觉得这个网站上的人喜欢给新人投反对票,而不是帮助他们。
  • @aashman 不正确。只是很多刚接触 StackOverflow 的人(以及它的合作伙伴网站)认为它是免费的调试服务,而不是社区驱动的知识资源。
  • 人们投了反对票,因为你给他们一个初学者问题,你可以用book自己回答。它会告诉你参数被复制了,你想用node* &amp;ptr替换node* ptr

标签: c++ recursion binary-search-tree


【解决方案1】:

您需要确保在分配新节点时更新父节点。一种方法是让 insert 返回节点指针:

node* insert(node* ptr, int num) {
        if (ptr == NULL) {
                ptr = new node;
                ptr->data = num;
                ptr->left = NULL;
                ptr->right = NULL;
        } else if (ptr->data >= num) {
                ptr->left = insert(ptr->left, num);
        } else {  // ptr->data < num 
                ptr->right = insert(ptr->right, num);
        }
        return ptr;
}

【讨论】:

  • 谢谢!那行得通。我最初尝试在该函数中传递一个指向节点的指针,但我想我忘了做点什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多