所以我有以下代码:
#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;
}
有人可以告诉我为什么在插入元素时,root仍然指向NULL而不是Node实例?我甚至检查当前指针的值,但它仍然因某种原因,当它应该是第一个被赋值的节点时,root为NULL
答案 0 :(得分:2)
有人可以告诉我为什么在插入元素时,root仍然指向NULL
您的功能BST::insert(int value)
不会修改root
。
这就是为什么root
仍为NULL。
使您的方法工作的一种方法是让current
指向您要修改的指针,而不是让current
< strong>持有该指针的副本。
答案 1 :(得分:1)
您正在更改Node*
指向的current
,但您从未触及根。
current = new Node(value);
为空,则 root = new Node(value);
应为root
。
此外,除了这里的问题之外,如果您使用递归调用进行插入和删除,您的代码将会更简单(当root
是{{1}}时,您不必担心这种情况指向null因为它将被隐式处理)