这两个程序有什么区别

What is the difference in these two program

我正在制作一个二叉树程序并且这个程序有效

#include <iostream>

using namespace std;

struct node{
    int data;
    node *left;
    node *right;
};



void insert( node **rootnode , int value) {

    node* newnode = *rootnode;

    if ( newnode == NULL ) {
        newnode = new node;
        newnode->left = NULL;
        newnode->right = NULL;
        newnode->data  = value;
        *rootnode = newnode; // this was missing!
    }
    else if ( value < newnode->data ){
        insert( &newnode->left , value );
    }
    else if ( value > newnode->data  ){
        insert ( &newnode->right , value );
    }


}

void inorder ( node *root ){
    if ( root == NULL ){
        return;
    }
    else{
        inorder( root->left );
        cout << root->data << endl;
        inorder( root->right );
    }
}




int main(){

    node* root = NULL;

    insert ( &root , 4);
    insert ( &root , 5);
    insert ( &root , 2 );
    insert( &root , 10 );
    insert( &root , 1 );

    //cout << root->data << endl;
    inorder( root );

}

现在我尝试在不传递根节点引用的情况下进行此操作...但它不起作用...我无法找到原因..

#include <iostream>
using namespace std;

struct node{
    int data;
    node *left;
    node *right;
};



void insert( node *rootnode , int value) {

    node* newnode = rootnode;

    if ( newnode == NULL ) {
        newnode = new node;
        newnode->left = NULL;
        newnode->right = NULL;
        newnode->data  = value;
        rootnode = newnode; // this was missing!
    }
    else if ( value < newnode->data ){
        insert( newnode->left , value );
    }
    else if ( value > newnode->data  ){
        insert ( newnode->right , value );
    }


}

void inorder ( node *root ){
    if ( root == NULL ){
        return;
    }
    else{
        inorder( root->left );
        cout << root->data << endl;
        inorder( root->right );
    }
}




int main(){

    node* root = NULL;

    insert ( root , 4);
    insert ( root , 5);
    insert ( root , 2 );
    insert( root , 10 );
    insert( root , 1 );

    //cout << root->data << endl;
    inorder( root );

}

第二个程序只是给出空白输出...我认为根节点没有更新..但我不知道为什么....

函数参数是函数的局部变量。他们获得相应参数值的副本。

你可以想象下面的函数声明

void insert( node *rootnode , int value);

及其调用

insert ( root , 4);

以下方式

void insert( /*node *rootnode , int value*/)
{
    node *rootnode = root;
    int value = 4;
    //...

退出函数后这些局部变量将被销毁。 varibale root 的原始值不会改变,因为该函数处理 root.

的副本

因此,如果您想在函数内更改传递给函数的任何对象,您需要在 C 含义或 C++ 含义中通过引用传递它。

也就是说,在 C 中,您传递一个指向对象的指针。在 C++ 中,您可以使用相同的方法或将相应的参数声明为引用。

所以在 C 中函数声明可以像这样

void insert( node **rootnode , int value) ;

而在 C++ 中,它可以看起来像上面或下面的方式

void insert( node * &rootnode , int value) ;