【问题标题】:Tree recursion c++ missing values of children nodes after end of function函数结束后子节点的树递归c ++缺失值
【发布时间】:2016-12-30 14:08:45
【问题描述】:

我需要一些关于我正在尝试编写的代码的帮助。我的想法是调用一个递归函数(在主函数中),它计算给定根的子节点,我通过引用传递该根,但是当递归函数结束时,子节点不会被存储。如果有人能告诉我我做错了什么,我将不胜感激。代码如下:

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

我不认为其他功能有问题,所以我也不会复制它们。

【问题讨论】:

    标签: c++ recursion tree


    【解决方案1】:

    在不详细了解TreeNode结构的情况下,我认为问题在于你push_back &amp;child作为参考,而child是一个本地/临时变量。

    我想你应该写:

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

    【讨论】:

    • 非常感谢!我忘了添加 TreeNode 类,是的,但它现在似乎工作正常!再次感谢! :)
    猜你喜欢
    • 2021-08-03
    • 2010-12-12
    • 2018-10-31
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多