繁体   English   中英

在二进制搜索树中插入节点时使用指针处理时出错

[英]Error when working with pointers in insertion of a node in a binary search tree

所以我有以下代码:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Node
{
    int value;
    Node *left = NULL;
    Node *right = NULL;
    Node(int value)
    {
        this->value = value;
    }
};
struct BST
{
    Node *root = NULL;
    void insert(int value)
    {
        cout<<"Inserting: "<<value<<endl;
        Node *current = root;
        while(current != NULL)
        {
            cout<<"YEA";
            if(value > current->value)
            {
                current = current->right;
            }
            else current = current->left;
        }
        current = new Node(value);
        cout<<"In the node val: "<<current->value<<endl;
        if(root == NULL)
        {
            cout<<"Root is NULL but it shouldn't\n";
        }
        cout<<"Root val: "<<root->value<<endl;

    }
    void remove(int value)
    {
        Node *toReplace = NULL;
        Node *toBeReplacedWith = NULL;
        toReplace = search(value);

        Node *current = toReplace->left;
        if(current == NULL) toBeReplacedWith = toReplace->right;
        else
        {
            while(current->right != NULL)
            {
                current = current->right;
            }
            toBeReplacedWith = current;
        }
        current->value = toBeReplacedWith->value;
        current->left = toBeReplacedWith->left;
        current->right = toBeReplacedWith->right;
        free(toBeReplacedWith);
    }
    Node* search(int value)
    {
        Node *current = root;
        while(current != NULL && current->value != value)
        {
            if(current->value > value) current = current->left;
            else current = current->right;
        }
        if(current == NULL)
        {
            cout<<"The node didn't exist in the BST";
        }
        return current;
    }
    void traverse()
    {
        rec_traverse(root);
    }
private:
    void rec_traverse(Node * current)
    {
        if(current == NULL) return;
        rec_traverse(current->left);
        cout<<current->value<<endl;
        rec_traverse(current->right);
    }
};
int main()
{
    BST tree;
    for(int i = 0; i < 10; ++i)
    {
        tree.insert(i);
    }
    tree.traverse();
    return 0;
}

有人可以告诉我为什么插入元素时根仍然指向NULL而不是Node实例吗? 我什至检查当前指针是否有值,并且具有,但由于某种原因,当根应该为第一个分配值的节点时,根为NULL

有人可以告诉我为什么插入元素时根仍然指向NULL

您的函数BST::insert(int value)绝对不会修改root

这就是为什么root保持NULL的原因。

使您的方法起作用的一种方法是让current 指向要修改的指针 ,而不是让current 持有该指针的副本

您正在更改current所指向的Node* ,但永远不要触摸根。

current = new Node(value); 应该是root = new Node(value); 如果root为null。

此外,除了这里的问题外,如果您使用递归调用进行插入和删除,则代码将更简单(并且您不必担心root指向null的情况,因为它会隐式处理)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM