gpt4 book ai didi

对二叉树中节点的双指针插入的用法感到困惑

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:53 24 4
gpt4 key购买 nike

所以这里是工作正常的函数:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com