我必须在每个节点中构建一个自定义数量为'sons'的树(带有指向节点'子'的指针的动态表):
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”添加到空树中,但第二个操作不正确。有人可以给我一个如何处理这种树的建议吗?如何向根添加新节点?
答案 0 :(得分: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;
答案 1 :(得分:0)
我认为n2 -> father = root
是错误的。 root是tree
的数据成员。你可以使用t1 -> root
来引用它。如果你想定义一个树,你只需要定义一个'Node'类,如下所示:
class Node
{
string data_;
std::vector<Node> children_;
public:
Node(string);
}
//
Node* root = new Node("root");
Node node = Node("child");
root -> children.insert(node);