【发布时间】:2022-01-13 06:38:34
【问题描述】:
我正在尝试插入 BST;
struct Node
{
Node* left;
Node* right;
int data;
Node(int d)
:left(nullptr), right(nullptr), data(d)
{
}
};
void Insertion(Node* head, int value)
{
if (!head)
{
head = new Node(value);
return;
}
if (head->data > value)
Insertion(head->left, value);
else
Insertion(head->right, value);
}
void printTree(Node* root)
{
if (!root)
{
return;
}
cout << root->data << " "; //20 15 10 18 30 35 34 38
printTree(root->left);
printTree(root->right);
}
int main()
{
Node *root = new Node(20);
Insertion(root, 15);
Insertion(root, 30);
Insertion(root, 10);
Insertion(root, 18);
Insertion(root, 35);
Insertion(root, 34);
Insertion(root, 38);
printTree(root);
}
我的Insertion 方法无法正确插入。但是如果我像下面这样使用它;
Node* Insertion(Node* head, int value)
{
if (!head)
{
return (new Node(value));
}
if (head->data > value)
head->left = Insertion(head->left, value);
else
head->right = Insertion(head->right, value);
return head;
}
我不确定Node* head 是否是我发送的内容的副本,如果是,是否可以在不使用节点返回类型但通过引用传递head 的情况下创建相同的函数?
【问题讨论】:
-
请记住,C++ 中的参数默认是按值传递。这意味着调用中使用的值将被复制到函数参数变量中,并且当函数返回时,对参数变量的任何修改(如对其赋值)都将丢失。请投资some decent books 并阅读references 以及如何通过引用传递参数。恰当的例子:在您分配给
head的Insertion函数中。当函数返回时,该赋值丢失。 -
head是一个值参数。当您从Insertion()返回时,它的修改将丢失。为了防止这种情况,您必须将其类型更改为Node*& head- 对节点指针的引用。另一种方法是在调用端应用Insertion()的返回值,因为这是之后Node* head的更新值,例如root = Insertion(root, 15);. -
@Scheff'sCat,谢谢
Node*& head我不知道指针也可以通过引用传递。 -
@Someprogrammerdude 谢谢你的链接,我会试试那里提到的一些书
-
虽然不能代替买一本好书,这里有一个在线教程的链接,它解释了通过by value、by pointer和by reference之间的区别。
标签: c++ pointers recursion reference pass-by-reference