0

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

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”添加到空树中有效,但第二个操作不正确。有人可以给我一个建议如何处理这种树吗?如何将新节点添加到根?

4

2 回答 2

0

我认为n2 -> father = root是错误的。root 是 的数据成员tree。你可以参考它使用t1 -> 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);
于 2013-12-18T14:03:07.910 回答
0

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

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;
于 2013-12-18T13:56:56.657 回答