我必须在每个节点中构建一个具有自定义数量的“儿子”的树(带有指向节点“儿子”的指针的动态表):
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”添加到空树中有效,但第二个操作不正确。有人可以给我一个建议如何处理这种树吗?如何将新节点添加到根?