BST没有添加元素

时间:2017-08-16 10:30:15

标签: c++ c++11 pointers binary-search-tree

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

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;
}

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

    else if(root==NULL)
        root = createLeaf(key);

为什么会这样?

1 个答案:

答案 0 :(得分:5)

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

void addElement(int key, nodePtr tempRoot){

您可以在此处使用参考资料。

void addElement(int key, nodePtr &tempRoot)
相关问题