[英]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.