【发布时间】:2020-07-26 17:25:03
【问题描述】:
以下是我的 BST 插入代码。我想使用 void 返回类型进行插入,而不是使用 'struct node*' 作为其返回类型的常规方式。我无法在其中找到错误或逻辑错误。有人可以详细解释为什么我的代码不起作用吗?
#include<iostream>
using namespace std;
struct node
{
int val;
node *left, *right;
};
void ins(int key, node *nroot)
{
if(nroot == NULL)
{
node *temp= new node;
temp->val=key;
temp->left=NULL;
temp->right=NULL;
nroot=temp;
}
else if(key > nroot->val)
{
ins(key, nroot->right);
}
else
{
ins(key, nroot->left);
}
}
void print(node *nroot)
{
if(nroot!=NULL)
{
print(nroot->left);
cout<<nroot->val;
print(nroot->right);
}
}
main()
{
int n;
cin>>n;
node *root= new node;
int x;
cin>>x;
root->left=NULL;
root->right=NULL;
root->val=x;
for(int i=1;i<n;i++)
{
cin>>x;
ins(x, root);
}
print(root);
}
【问题讨论】:
-
nroot=temp;赋值给局部变量;此分配对调用者不可见。当您调用ins(key, nroot->right)时,无论ins、nroot->right内部发生什么,仍然是NULL。 -
在
void ins(int key, node *nroot)nroot是按值传递,而不是按引用传递。是的,它是一个指针,但指针是一个普通的旧变量,其值是另一个对象的地址。另一个对象是通过引用传递的。指针本身仍然是按值传递的,所以你将它指向其他地方,你只是改变了一个副本。
标签: c++ tree binary-search-tree