BST没有添加元素

Shu*_*and 0 c++ pointers binary-search-tree c++11

所以我编写了这段代码来将元素添加到二叉树中.如下图所示.

typedef struct node{
    int key;
    node *right;
    node *left;
}*nodePtr;

nodePtr root = NULL // As global variable.

void addElement(int key, nodePtr tempRoot){
    if(tempRoot!=NULL){
        if(tempRoot->key > key){
            if(tempRoot->left!=NULL)
                addElement(key, tempRoot->left);
            else
                tempRoot->left = createLeaf(key);
        }
        else if(tempRoot->key < key){
            if(tempRoot->right!=NULL)
                addElement(key, tempRoot->right);
            else
                tempRoot->right = createLeaf(key);
        }
    }else if(tempRoot==NULL)
        tempRoot = createLeaf(key);
}

int main(){
    int arr[] = {50,45,23,10,8,1,2,54,6,7,76,78,90,100,52,87,67,69,80,90};

    for(int i=0; i<20; i++){
        addElement(arr[i], root);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是当我尝试打印树时,此代码不会向树中添加任何内容.但是,如果我用此代码替换代码的最后部分;

    else if(root==NULL)
        root = createLeaf(key);
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Gau*_*gal 5

您通过值接收tempRoot,因此在函数内部更改它将不会反映在外部.当您直接访问全局时root,您确实可以在函数内部更改其值.

void addElement(int key, nodePtr tempRoot){
Run Code Online (Sandbox Code Playgroud)

你可以在这里使用引用.

void addElement(int key, nodePtr &tempRoot)
Run Code Online (Sandbox Code Playgroud)