2013-12-18 40 views
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」添加到空樹中,但第二個操作不正確。有人能給我一個建議如何處理這種樹嗎?如何向根添加新節點?

回答

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; 
+0

在節點的構造函數中?它不工作在QT創作者我有一個錯誤消息「沒有匹配函數調用'節點::節點()'」。我認爲這是行不通的,因爲在行「sons [i] = new node()」中,我們不給任何參數給我們構建的對象... – user3115426

+0

好吧,我設法通過在構造函數中添加以下行來修復此節點類: sons =新節點* [number_of_sons]; – user3115426

0

我覺得n2 -> father = 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);