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」を追加すると機能しますが、2 番目の操作は正しくありません。この種の木の扱い方について誰かアドバイスをもらえますか?ルートに新しいノードを追加する方法は?

4

2 に答える 2

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);
于 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 に答える