【问题标题】:BST not adding elementsBST不添加元素
【发布时间】:2017-08-16 10:30:14
【问题描述】:

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

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

为什么会这样?

【问题讨论】:

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


    【解决方案1】:

    你通过值接收tempRoot,所以在函数内部改变它不会反映在外部。而且当你直接访问全局root时,你确实可以在函数内部改变它的值。

    void addElement(int key, nodePtr tempRoot){
    

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

    void addElement(int key, nodePtr &tempRoot)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      相关资源
      最近更新 更多