我是C ++的新手,每当我向树中添加任何东西时,我都无法找到为什么树的根会发生变化。它必须是一个指针问题,但我无法弄明白。例如:
BST bst;
bst.insert(5);
bst.insert(2);
当我插入5时,我得到正确的输出,但是当我插入2时,它说:
Inserted 2 to the left of 2.
节点类:
class Node
{
// Let BST directly access members.
friend class BST;
public:
// Constructor
Node(int i);
int getValue();
protected:
int value;
Node *left;
Node *right;
};
// Constructor
Node::Node(int i)
{
value = i;
left = 0;
right = 0;
}
int Node::getValue()
{
return value;
}
BST课程:
class BST
{
public:
BST();
void insert(int i);
void print();
void print(Node *n);
private:
// root of the tree
Node *root;
};
BST::BST()
{
root = 0;
}
void BST::insert(int i)
{
Node *cur = this->root;
Node *prev;
Node new_node(i);
if(cur == 0)
{
this->root = &new_node;
cout << "Root is empty, insert " << this->root->value << " as root." << endl;
return;
}
while(cur != 0)
{
prev = cur;
if(i <= cur->value)
{
cur = cur->left;
if(cur == 0)
{
prev->left = &new_node;
cout << "Inserted " << prev->left->value << " to the left of " << prev->value << endl;
return;
}
}
else if(i > cur->value)
{
cur = cur->right;
if(cur == 0)
{
prev->right = &new_node;
cout << "Inserted " << prev->right->value << " to the right of " << prev->value << endl;
return;
}
}
}
}
void BST::print()
{
print(this->root);
}
void BST::print(Node *n)
{
if(n == 0)
{
return;
}
print(n->left);
cout << n->value << " " << endl;
print(n->right);
}
感谢。
答案 0 :(得分:4)
Node new_node(i);
这会创建一个局部变量。稍后您将其地址分配给root
。请注意,使用在其范围之外的局部变量的地址处写入的数据将调用未定义的行为。您需要分配动态内存,然后注意释放它。
答案 1 :(得分:1)
您正在存储本地对象的地址:
Node new_node(i);
...
this->root = &new_node;
当本地对象超出范围时,进一步使用该地址是未定义的行为。
你想:
Node* new_node = new Node(i);
...
this->root = new_node;
等