C ++在树中设置父节点

时间:2017-05-24 16:12:49

标签: c++ tree

我有以下课程:

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()? 谢谢。

1 个答案:

答案 0 :(得分:0)

显然,你的

node->setLeftChild(node);

会产生废话。您必须编写有效代码或(至少在DEBUG模式下)防止此类无意义

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();