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

标签 c pointers binary-tree double-pointer

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

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/

相关文章:

c 编程 : need fresh eyes to look at this [demo code ! = 作业]

c++ - 为什么编译器允许你在这里 "write"一个 const 变量?

c++ - 从函数获取输出动态分配数组的更好变体?

java - 基于 ArrayList 的二叉树 - Java

c - malloc困惑

c - 指针向上转换和向下转换

algorithm - 给出 n 节点二叉搜索树高度的渐近上界,其中节点的平均深度为 Θ(lg n)

java - 检查异常后程序抛出异常

占位符可以与 fgets 一起使用吗?

c++ - 将大型 char8 c 数组转换为 short16 的最快方法是什么?