我正在创建一个函数来在二叉树中插入一个元素,首先,我在 Visual Studio 2012 上执行了以下操作:
void Insert(Nodo *root, int x){
if(root == NULL){
Nodo *n = new Nodo();
n->value = x
root = n;
return;
}
else{
if(root->value > x)
Insert(&(root)->left, x);
else
Insert(&(root)->right, x);
}
}
但同样的代码在 Dev-C++ 中不起作用,我需要使用 Pointer of Pointer 来使其工作,如下所示:
void Insert(Nodo **root, int x){
if(*root == NULL){
Nodo *n = new Nodo();
n->value = x
*root = n;
return;
}
else{
if((*root)->value > x)
Insert(&(*root)->left, x);
else
Insert(&(*root)->right, x);
}
}
有谁知道为什么会发生?
第一个代码不应编译。事实上它不能在 MSVC 2013 下编译。
Why ?
你的节点结构应该是这样的:
struct Nodo {
int value;
Nodo*left, *right; // pointer to the children nodes
};
这意味着(root)->left
属于类型Nodo*
。因此&(root)->left
属于类型Nodo**
这是不兼容的Nodo*
争论。
不管怎样,在你的插入函数中,你肯定想改变树。但如果你这样做:root = n;
您只需更新根参数(指针)。一旦您离开该功能,此更新就会丢失。在这里,您当然想要更改根节点的内容或更可能更改指向根节点的指针。
在第二个版本中,您将指向节点的指针的地址作为参数传递,然后在必要时更新该指针(预期行为)。
Remark
如果您想通过引用进行传递,则可以“保存”第一个版本:
void Insert(Nodo * &root, int x){ // root then refers to the original pointer
if(root == NULL){ // if the original poitner is null...
Nodo *n = new Nodo();
n->value = x
root = n; // the orginal pointer would be changed via the reference
return;
}
else{
if(root->value > x)
Insert(root->left, x); // argument is the pointer that could be updated
else
Insert(root->right, x);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)