C ++递归 - 按顺序将树数据添加到列表中

时间:2013-05-09 23:19:50

标签: c++ list recursion

我的代码如下 - 我正在尝试将我从二叉树中依次获得的飞机列表(从小到大)回到我的主要列表。对于下面的代码,我得到根节点两次。我已经工作了好几个小时......有什么建议吗?

谢谢, 夏洛特

std::list<Aircraft> Tree::buildList()
{
    std::list<Aircraft> aircraftList;
    if (_root != 0)
    {
        aircraftList = buildListHelp(_root, aircraftList);
        aircraftList.push_front(*_root->getAircraftData());     
    }
    return aircraftList;
}

std::list<Aircraft> Tree::buildListHelp(Node* node, std::list<Aircraft> aircraftList)
{
    //aircraftList.push_back(*node->getAircraftData())
    /*if (node->getLeft() != 0)
    {*/
    if (node==0)
        return aircraftList;
    buildListHelp(node->getLeft(), aircraftList);
    //}
    aircraftList.push_back(*node->getAircraftData());
    /*if (node->getRight() != 0)
    {*/
    buildListHelp(node->getRight(), aircraftList);  
    //}
    return aircraftList;
}

1 个答案:

答案 0 :(得分:0)

假设_root被声明为

Node* _root;

你要推两次:

aircraftList.push_front(*_root->getAircraftData());    
aircraftList.push_back(*node->getAircraftData());

第一次调用buildListHelp