C++ 二叉搜索树,不能做遍历
请参阅下面的BST代码。它只输出“5”。我做错了什么C++ 二叉搜索树,不能做遍历,c++,g++,C++,G++,请参阅下面的BST代码。它只输出“5”。我做错了什么 #include <iostream> class bst { public: bst(const int& numb) : root(new node(numb)) {} void insert(const int& numb) { root->insert(new node(numb), root); } void inorder() { root->inor
#include <iostream>
class bst {
public:
bst(const int& numb) : root(new node(numb)) {}
void insert(const int& numb) {
root->insert(new node(numb), root);
}
void inorder() {
root->inorder(root);
}
private:
class node {
public:
node(const int& numb) : left(NULL), right(NULL) {
value = numb;
}
void insert(node* insertion, node* position) {
if (position == NULL) position = insertion;
else if (insertion->value > position->value)
insert(insertion, position->right);
else if (insertion->value < position->value)
insert(insertion, position->left);
}
void inorder(node* tree) {
if (tree == NULL)
return;
inorder(tree->left);
std::cout << tree->value << std::endl;
inorder(tree->right);
}
private:
node* left;
node* right;
int value;
};
node* root;
};
int main() {
bst tree(5);
tree.insert(4);
tree.insert(2);
tree.insert(10);
tree.insert(14);
tree.inorder();
return 0;
}
#包括
bst级{
公众:
bst(const int&numb):根(新节点(numb)){}
无效插入(常量int和numb){
根->插入(新节点(numb),根);
}
无效顺序(){
根->索引(根);
}
私人:
类节点{
公众:
节点(常量int和numb):左(空)、右(空){
价值=麻木;
}
空心插入(节点*插入,节点*位置){
如果(位置==NULL)位置=插入;
否则如果(插入->值>位置->值)
插入(插入,位置->右侧);
否则如果(插入->值<位置->值)
插入(插入,位置->左);
}
无效索引(节点*树){
if(tree==NULL)
返回;
顺序(树->左);
std::cout value right);
}
私人:
节点*左;
节点*右;
int值;
};
节点*根;
};
int main(){
bst树(5);
树。插入(4);
树。插入(2);
树。插入(10);
插入(14);
tree.inoorder();
返回0;
}
使用参考:
空心插入(节点*插入、节点*&位置)
void顺序(节点*&树){使用引用:
空心插入(节点*插入、节点*&位置)
按顺序无效(节点*&树){这是因为您从未设置
根的左和右字段的值
您必须说,对于给定节点,n
:
n->left = ...
n->right = ...
你从来没有这样做过。所以你得到了一个节点树。你的根有两个空的子节点
你也可以偷偷摸摸地做这件事:如果你按照@user1431015的建议做,并通过引用传递子指针,那么分配给引用助手(位置
)按值传递它们,就像你做的那样,只分配给一个局部变量,而不是树本身。这是因为你从来没有设置根的左
和右
字段的值
您必须说,对于给定节点,n
:
n->left = ...
n->right = ...
你从来没有这样做过。所以你得到了一个节点树。你的根有两个空的子节点
你也可以偷偷摸摸地做这件事:如果你按照@user1431015的建议做,并通过引用传递子指针,那么分配给引用助手(位置
)将完成此操作。按值传递它们,就像您所做的那样,只分配给局部变量,而不分配给树本身。在大多数情况下,您的插入永远不会完成任何操作。递归的基本情况是:
void insert(node* insertion, node* position) {
if (position == NULL) position = insertion;
但所有的“位置”都是一个局部范围的指针值。一旦函数退出,分配给它将没有任何效果
您需要做的是将位置参数设置为指针的引用。换句话说,将其设置为节点*&
类型。然后,在退出函数后,赋值将保持不变。在大多数情况下,插入操作永远不会结束。递归的基本情况是:
void insert(node* insertion, node* position) {
if (position == NULL) position = insertion;
但所有的“位置”都是一个局部范围的指针值。一旦函数退出,分配给它将没有任何效果
您需要做的是将位置参数设置为指针的引用。换句话说,将其设置为node*&
类型。然后在退出函数后,赋值将保持不变。您能解释一下为什么需要在此处使用引用吗?@ihm,因为您正在修改指针“root”的内容。因此insert的第二个参数应该是引用。“inorder”中的参数不必是引用。您能解释一下为什么我们需要在这里使用引用吗?@ihm,因为您正在修改指针“root”的内容。因此insert的第二个参数应该是引用。“inorder”中的参数不必是引用。