【问题标题】:Custom tree handling自定义树处理
【发布时间】:2014-01-22 07:55:29
【问题描述】:

我必须在每个节点中构建一个具有自定义数量的“儿子”的树(带有指向节点“儿子”的指针的动态表):

class node{
   public
   string data;
   int number_of_sons;
   struct node *father, **sons; // **sons is table of pointers to the "sons" of the node;

   node(string s, int n) : data(s), number_of_sons(n){   
   }//constructor

};

和列表类:

class tree{
   public:
   node *root;
   tree() : root(NULL){
   }
};

我以这种方式创建树和树的节点:

tree t1 = new tree();
node n1 = new node("example1", 1);
node n2 = new node("example2", 2);
node n3 = new node("example3", 1);
node n4 = new node("example4", 3);

我正在尝试以“手动”方式将它们插入到树中,但这是行不通的:

n1->father = NULL;
t1->root = n1;

//adding the second object to the tree:
n2->father = root;
t1->root->sons[0] = n2;

将“n1”添加到空树中有效,但第二个操作不正确。有人可以给我一个建议如何处理这种树吗?如何向根添加新节点?

【问题讨论】:

    标签: c++ data-structures tree dynamic-tables


    【解决方案1】:

    你应该为儿子分配空间。您可以将向量用于儿子,也可以将其保存在数组中,例如: 在构造函数中:

    sons = new node[SIZE];
    for(int i=0;i<SIZE;i++)
      sons[i]= new node();
    

    然后代码:

    n1->father = NULL;
    t1->root = n1;
    
    //adding the second object to the tree:
    n2->father = root;
    t1->root->sons[0] = n2;
    

    【讨论】:

    • 在节点的构造函数中?它在 qt creator 中不起作用我有一条错误消息“没有匹配的函数用于调用 'node::node()'”。我认为它不起作用,因为在“sons [i] = new node()”行中,我们没有为我们构建的对象提供任何参数...
    • 好的,我设法通过在构造函数中添加这一行来修复这个节点类:sons = new node * [number_of_sons];
    【解决方案2】:

    我认为n2 -&gt; father = root 是错误的。 root 是tree 的数据成员。你可以参考它使用t1 -&gt; root。如果你想定义一棵树,你只需要像这样定义一个“节点”类:

    class Node
    {
        string data_;
        std::vector<Node> children_;
    
    public:
        Node(string);
    } 
    
    //
    
    Node* root = new Node("root");
    Node node = Node("child");
    root -> children.insert(node);
    

    【讨论】:

      猜你喜欢
      • 2014-02-23
      • 2011-01-30
      • 2021-10-10
      • 2018-05-28
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多