【问题标题】:How to create a tree in C++?如何在 C++ 中创建树?
【发布时间】:2016-10-07 10:00:50
【问题描述】:

我想在C++ 中创建一棵树。我有父子关系和节点数,我想以某种方式存储这棵树。例如,如果我有一个图,我可以将它与邻接列表一起存储,或者使用向量的向量或邻接矩阵。但是树呢?

例如,我有 9 个节点和 9-1=8 父子关系:7-2, 7-3, 7-4, 3-5、3-6、5-8、5-9、6-1。我想存储这棵树,例如计算从最老的父 (7) 到孩子的最长路径(在本例中为 7-3-5-87-3-5-9,路径长度为4)。

【问题讨论】:

  • 任何无环无向连通图都是一棵树。您可以像存储图表一样存储树。

标签: c++ data-structures tree graph-theory


【解决方案1】:

假设您的图是有向图并且您不知道节点的数字范围,我建议您使用map<int, vector<int> > 作为您的邻接列表:

#include <vector>
#include <map>
#include <iostream>

using namespace std;

int main()
{
    map< int, vector<int> > adj_list;

    int edges;
    cin >> edges;
    for ( int i=0; i<edges; ++i ){
        int u, v;
        cin>>u>>v;
        adj_list[u].push_back(v);
        //adj_list[v].push_back(u); // uncomment this line if your graph is directed
    }

    for ( auto it = adj_list.begin(); it != adj_list.end(); ++it ){
        const auto& children = it->second;
        cout << "children of " << it->first << " is:" << endl;
        for ( int i=0; i < children.size(); ++i ){
            cout << children[i] << " ";
        }
        cout << endl;
    }
}

输入

8
7 2
7 3
7 4
3 5
3 6
5 8
5 9
6 1

输出

children of 3 is:
5 6 
children of 5 is:
8 9 
children of 6 is:
1 
children of 7 is:
2 3 4 

使用这种结构,map 的每个 key 都以vector&lt;int&gt; 的形式保存该节点的邻接列表。这意味着你可以通过遍历adj_list[1]来访问节点1的子节点。

【讨论】:

    【解决方案2】:

    我会通过让一个节点包含一个指向节点的(智能)指针向量来存储一棵树。例如:

    struct tree_node
    {
        int value;
        std::vector<std::unique_ptr<tree_node>> children;
    };
    

    【讨论】:

    • 我如何使用一个特定的节点及其关系?
    • 我不明白这个问题。
    【解决方案3】:

    如果我有一个图,我可以将它与邻接列表一起存储,或者使用向量的向量或邻接矩阵。但是树呢?

    但是a tree is a type of graph.

    Boost.Graph 文档中甚至有一个关于(家谱)树的具体示例,用于其邻接列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2015-05-21
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多