【问题标题】:populate n-ary tree using tree.hh STL Like使用 tree.hh STL 填充 n 叉树
【发布时间】:2012-05-02 01:41:02
【问题描述】:

我如何使用tree.hh: an STL-like C++ tree class 填充我的树并获得下面的树。一些帮助将不胜感激。 A 和 G 是根节点 谢谢

            A            G
      ______|____        |
     /      |    \       |
    B       C     D      H
    |       |     |      |
    |       E     |      |
     \_____/      |      |
        |         |      |
        F         |      |
        |_________|______|
           |
           I
           |
           J

在上面的代码中,我使用深度优先搜索来枚举列表中的项目。我很少有像这样格式化的数据

typedef tree<std::string> TreeNode;
typedef struct
{
    int   nBases;
    char * name;
} BASES;
BASES rgbases[] =
{
    {0xB, "J"},
    {0xA, "I"},
    {0x1, "H"},{0x0, "G"},
    {0x5, "F"},{0x2, "E"},{0x1, "C"},{0x0, "A"},
    {0x1, "D"},{0x0, "A"},
    {0x1, "B"},{0x0, "A"}
};

//here i'm trying to populate my tree
void populateTree(TreeNode &tr, BASES *pBaseArray, int numBase)
{
    int n = 0;
    while ( n < numBase )
    {
        BASES *pBase = &pBaseArray[n];
        if ( pBase->nBases > 0) // Check for children of the new node
            populateTree(tr, pBaseArray + (n + 1),pBase->nBases);
        // i suppose i need to insert tree code part here
        n += pBase->nBases + 1;
    }
}
void BuildTree(TreeNode &tr)
{
    populateTree(tr, rgBases, _countof(rgBases));
}

【问题讨论】:

  • 据我所知,tree.hh 无法为您提供图表。您可以考虑使用boost graph
  • 谢谢,重播,我想先创建我的树,如果有必要,我会使用图表。
  • 我很困惑。在tree 中,每个节点最多有一个父节点。但是您的A 节点似乎有三个。

标签: c++ tree


【解决方案1】:

可以通过删除连接节点 A 与 B 和 D 的边(或者可能是连接节点 A 与 C 和 D 的边)来获得一棵跨越所呈现的原始图的树。然后树类将适用:

            A            G                                   A            G 
            |            |                             ______|            |
            |            |                            /                   |
    B       C     D      H                           B       C     D      H 
    |       |     |      |                           |       |     |      | 
    |       E     |      |                           |       E     |      | 
    \______/      |      |                           \______/      |      |
        |         |      |                              |          |      |
        F         |      |                              F          |      |
        |_________|______|                              |__________|______| 
           |                                                | 
           I                                                I
           |                                                |
           J                                                J 

上述树中引起循环的边,可以单独记录,即 AB 和 AD,除了树类之外,可以在一个结构中记录。用这种结构合并树将恢复原始图。

【讨论】:

  • 我绘制的树只是我所有数据的一部分。但都具有 sama 格式。你能用我的代码告诉我如何处理它吗?我不知道它是否是递归的,我可以处理继承。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
相关资源
最近更新 更多