所以这里是工作正常的函数:
void Insert(node ** root, int inpdata){//tree's root should be passed here
if(*root == NULL){
*root = createNode(inpdata);
}
else if(inpdata < (*root)->data){
Insert(&(*root)->left,inpdata);
}
else{
Insert(&(*root)->right,inpdata);
}
}
但我不明白为什么我们必须使用双指针。例如,为什么以下代码不起作用:
void Insert(node * root, int inpdata){//tree's root should be passed here
if(root == NULL){
root = createNode(inpdata);
}
else if(inpdata < root->data){
Insert(root->left,inpdata);
}
else{
Insert(root->right,inpdata);
}
}
另外,在第一个函数中,我无法理解 &(*root)
的用法。那不是没有意义吗,因为 *root
本身就是一个指针。因此,“指针的地址”是多余的,因为指针已经存储了地址值。我可能有点困惑,所以非常感谢您的帮助。
谢谢!
最佳答案
C 按值传递参数,如果你使用第二种方法:
void Insert(node * root, int inpdata);
调用该函数后,调用方的root
不受影响。
I could not comprehend the usage of &(*root)
你被precedence搞糊涂了并错误地解析表达式。 &(*root)->left
是
&((*root)->left).
关于对二叉树中节点的双指针插入的用法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347451/