2017-05-24 30 views
-3

設置父節點我有下面的類:C++在樹上

class Node 
{ 
    private: 
    Node* leftChild; 
    Node* rightChild; 
    Node* father; 
    public: 
    Node() { leftChild = rightChild = father = NULL; };  
    Node* getLeftChild() { return leftChild; }; 
    Node* getRightChild() { return rightChild; }; 
    Node* getFather() { return father; } 
    void setRightChild(Node* child) { rightChild = child; } 
    void setLeftChild(Node* child) { leftChild = child; }; 
    void setFather(Node* f) { father = f; }; 
}; 

設置左子和右子的時候我會還設置了父節點。我嘗試:

void setLeftChild(Node* child) 
{ 
    leftChild = child; 
    child->setFather(this); 
};  

Node* node = new Node(); 
Node* node2 = new Node(); 

node->setLeftChild(node2); 

由於錯誤的使用,我收到一個隨機錯誤。我應該如何設置功能setLeftChild()setRightChild()? 謝謝。

+0

爲什麼不是母節點?這是性別歧視。這就是我們稱之爲父母的原因。 *觸發* – arminb

+0

請詳細說明錯誤 – noelicus

+0

您可能會發現**很多**更容易使用標準容器,例如['std :: deque <>'](http://en.cppreference.com/ w/cpp/container/deque) –

回答

0

顯然,你

node->setLeftChild(node); 

會產生廢話。您必須編寫有效的代碼或(至少在調試模式下)警惕這樣的廢話

void setLeftChild(Node* child) 
{ 
    if(child==this) 
    throw std::runtime_error("node cannot be its own child"); 
    leftChild = child; 
    child->setFather(this); 
};  

另一個想法是讓father有在施工中提供(和等於nullptr只有一個不變的成員根節點),即

struct Node 
{ 
    Node*const father;  // immutable, so might as well be public 
    Node(Node*f) : father(f) {} 
    Node*MakeLeftChild() // create left child and return it 
    { 
    if(!leftChild) 
     leftChild = new Node(this); 
    return leftChild; 
    } 
    Node*MakeRightChild() // create right child and return it 
    { 
    if(!rightChild) 
     rightChild = new Node(this); 
    return rightChild; 
    } 
private: 
    Node*leftChild=nullptr; // defaults to having no children 
    Node*rightChild=nullptr; 
}; 

auto root = new Node(nullptr); 
auto node = root->MakeLeftChild(); 
node = node->MakeRightChild(); 
+0

如果我寫child-> setFather(this);該程序卡住了。 – Discipulos