【发布时间】:2020-10-09 01:42:49
【问题描述】:
我正在尝试实现一个将节点插入二叉搜索树的函数。我正在使用以下代码,但是当我尝试打印到屏幕时,我看到的只是“root = 1”。关于我做错了什么有什么建议吗?
#include <iostream>
class BTNode {
public:
int item;
BTNode *left;
BTNode *right;
BTNode(int i, BTNode *l=nullptr, BTNode *r=nullptr):item(i),left(l),right(r){}
};
BTNode *root = nullptr;
void insert(int i) {
if (root==nullptr)
root=new BTNode(i);
else if(i<root->item){
root=root->left;
insert(i);
}
else{
root=root->right;
insert(i);
}
}
int main()
{
insert (5);
insert (10);
insert (1);
if (root)
{
std::cout << "root = " << root->item << std::endl;
if (root->left)
std::cout << "root->left = " << root->left->item << std::endl;
if (root->right)
std::cout << "root->right = " << root->right->item << std::endl;
}
return 0;
}
【问题讨论】:
-
您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?。
-
与your rubber duck.讨论
root=root->left;的效果 -
通过查看您的代码,您的
insert函数似乎正在正确地将新节点添加到树中。但是,作为副作用,它有时会将全局变量root更改为根的左侧或右侧节点,从而导致树的其余部分丢失。你的insert函数永远不应该改变根,除非root == nullptr。 -
不要将
root设为全局变量,您可能希望将其设为main的局部变量并将其作为函数参数传递给insert。这也将使递归函数调用更容易。 -
建议:摆脱全局
root。它以多种方式使您变得更加困难(例如,您不能同时拥有两个 BST)并且可能成为调试的噩梦。通过引用传递节点,例如void insert(BTNode* & location, int i)