C ++:我的新节点在哪里?

时间:2014-10-02 17:15:37

标签: c++ set binary-tree

我正在尝试使用二进制树在Set中添加元素:

bool TreeSet::add(const string &str)
{
    if (treesize == 0)
    {
        TreeNode->data = str;
        treesize++;
        return true;
    }
    else
    {
        if (str < TreeNode->data)
            return insert(TreeNode->left, str);
        else if (str > TreeNode->data)
            return insert(TreeNode->right, str);
        else
            return false;
    }
    return false;
}

bool TreeSet::insert(TREE *node, const string &str) //private
{
    if (node == NULL)
    {
        node = new TREE;
        node->data=str;
        node->left = NULL;
        node->right = NULL;
        treesize++;
        return true;
    }
    else
    {
        if (str < node->data)
            return insert(node->left, str);
        else if (str > node->data)
            return insert(node->right, str);
        else
            return false;
    }
    return false;
}

正如您所看到的,我想在insert中初始化一个TREE结构,当我完成这个操作时,我想将它与树的左或右节点链接。

但是当我gdb这个时,只能构建1级树(顶级),*left*right节点都是NULL,无论我尝试了多少个字符串添加到它。为什么呢?

我的树是:

typedef struct tree
{
    string data;
    tree *left;
    tree *right;
} TREE;

2 个答案:

答案 0 :(得分:6)

bool TreeSet::insert(TREE *node

应该是

bool TreeSet::insert(TREE *&node

指针也可以通过引用传递,如果您打算直接修改它们应该是。否则你通过副本,你现在有两个指针指向同一位置。当您使用复制的一个数据向new提取某些数据时,它现在指向一个新的内存位置,将原始指针保持为NULL(C ++ 11中的nullptr


另外,在构建树时,您可能应该将leftright初始化为NULL(C ++ 11中的nullptr):

typedef struct tree
{
    string data;
    tree *left;
    tree *right;
    tree():left(NULL),right(NULL){}
} TREE;

答案 1 :(得分:2)

当您将指针作为参数传递给函数insert时,如下所示:

bool TreeSet::insert(TREE* node, const string& str);

然后将指针复制到参数node中。将node指向其他内容仅指向指针的本地副本。从调用站点传递给函数的指针未更改

node = new TREE; // Points local variable 'node' to newly allocated data.
                 // When the function goes out of scope 'node' will be destroyed
                 // and the memory will be leaked.

要更改原始调用网站指针指向的位置,请通过引用(或添加其他级别的间接)获取参数:

bool TreeSet::insert(TREE*& node, const string& str);

通过引用获取参数,确保您正在访问调用站点变量而不是本地副本。