2017-05-24 58 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