gpt4 book ai didi

c++ - 在二叉搜索树中插入节点时使用指针时出错

转载 作者:行者123 更新时间:2023-11-28 00:26:47 25 4
gpt4 key购买 nike

所以我有以下代码:

#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 实例吗?我什至检查了当前指针的值,它有,但由于某种原因,当它应该是第一个被赋值的节点时,root 仍然是 NULL

最佳答案

Can somebody tell me why when inserting an element the root still points to NULL

您的函数 BST::insert(int value) 在任何时候都不会修改 root

这就是为什么 root 保持为 NULL。

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

关于c++ - 在二叉搜索树中插入节点时使用指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24640872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com