[英]C++: Pointer vs Pointer of Pointer to insert a node in a Binary Tree
我正在创建一个在二叉树中插入元素的函数,首先,我在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 ++中不起作用,我需要使用指针指针使其工作,如下所示:
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下编译。
为什么?
您的节点结构应该是这样的:
struct Nodo {
int value;
Nodo*left, *right; // pointer to the children nodes
};
这意味着(root)->left
的类型为Nodo*
。 因此&(root)->left
是Nodo**
类型,它与Nodo*
参数不兼容。
无论如何,在你的插入函数中,你当然想要更改树。 但是如果你做的话: root = n;
你只需更新根参数(指针)。 离开该功能后,此更新将丢失。 在这里,您当然希望更改根节点的内容,或者更可能更改指向根节点的指针。
在第二个版本中,您将指向节点的指针的地址作为参数传递,然后在必要时更新此指针(预期行为)。
备注
第一个版本可以“保存”,如果你想通过引用传递:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.