指向struct作为函数参数的指针 - 为什么它的值不更新?

时间:2016-10-16 14:08:00

标签: c++ pointers

我尝试从空根指针开始构建二叉树,但树不会出现。但是,当我首先将任何叶子添加到树中时,一切正常。我的问题是,插入函数有什么问题,根指针没有更新?

#include<iostream>
using namespace std;
struct BTree
{
    int value;
    BTree *left;
    BTree *right;
};

BTree* newLeaf(int _value)
{
    BTree *p;
    p = new BTree;
    p -> value = _value;
    p -> left = nullptr;
    p -> right = nullptr;
    return p;
}

void insert(BTree *root, int _value)
{
    if (root == nullptr)
    {
        root = newLeaf(_value);
        /*why after entering here root is still nullptr*/
        cout << "entered" << endl;
        return;
    }

    if (root -> value == _value)
    {
        return;
    }
    else if (root -> value > _value)
    {
        if (root -> left == nullptr)
        {
            root -> left = newLeaf(_value);
            return;
        }
        else
        {
            insert(root -> left, _value);
        }
    }
    else
    {
        if (root -> right == nullptr)
        {
            root -> right = newLeaf(_value);
            return;
        }
        else
        {
            insert(root -> right, _value);
        }
    }
}

void print(BTree *root, int i)
{   
    if (root == nullptr)
    {
        return;
    }

    cout << "Level :" << i << " " << root -> value << endl;

    print(root -> left, i + 1);
    print(root -> right, i + 1);

}

int main(){
    /*1. that works properly */ 
    /*BTree *root = newLeaf(10);*/

    /*2. that does not work */
    BTree *root = nullptr;
    insert(root, 10);

    /*rest of code*/
    insert(root,5);
    insert(root,1);
    insert(root,3);
    insert(root,12);
    insert(root,11);
    insert(root,13);

    print(root, 0);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

root = newLeaf(_value);

由于root按值传递给insert(),因此无效。这会将root参数设置为insert(),但root()中的main对象保持不变。这是一个不同的对象。这就是“通过价值”的意思。

您需要通过引用传递指针:

void insert(BTree *&root, int _value)

顺便说一下,在进行递归调用之前,不再需要检查leftright子节点是否为空。