vixenn
vixenn

Reputation: 197

Tree recursion c++ missing values of children nodes after end of function

I need some help with a code I am trying to write. My idea is to call a recursive function (in the main function), which computes the child nodes to a given root, which root I pass by reference, but when the recursive function is over, the children are not stored. I would appreciate it if someone could tell me what I am doing wrong. Here is the code:

struct TreeNode
{
    string label;
    TreeNode* parent;
    vector<TreeNode*> children;
    string value;
};

void id3(vector<string> attributes, vector<int> attributes_sizes, vector<Data> set, TreeNode &root)
{
    // .. some other code goes here

    for(int i = 0; i < current_attribute_size; i++)
    {
        if(final_entropy[i].second == 0.0 && final_result[i].second.size() > 0)
        {
            TreeNode child;
            child.label = final_result[i].first;
            child.parent = &root;
            root.children.push_back(&child);
            child.value = final_result[i].second[0].node_caps; 
        }
        else if(final_result[i].second.size() > 0 && attributes.size() > 0)
        {
            TreeNode child;
            child.label = final_result[i].first;
            child.parent = &root;
            root.children.push_back(&child);
            id3(attributes, attributes_sizes, final_result[i].second, child); 
        }
    }
    return;
}

int main()
{
    // .. some other code goes here for the other arguments passed to id3

    TreeNode root;
    id3(attributes, attributes_sizes, educational, root);

    return 0;
}

I do not thinks that the other functions are the problem so I won't copy them too.

Upvotes: 1

Views: 275

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

Without knowing the TreeNode structure in detail, I think the problem is that you push_back &child as reference, and child is a local/temporary variable.

I suppose you should write:

TreeNode *child = new TreeNode();
child->label = ...
root.children.push_back(child);

Upvotes: 1

Related Questions