使用唯一指针向树添加节点

时间:2017-09-07 20:03:19

标签: c++ smart-pointers

我是智能指针的新手,我正在尝试创建一个双树,其中子节点通过唯一指针从父节点指向,并且子节点通过原始指针指向父节点。因此,当父节点被销毁时,整个子树将在此过程中被销毁。

class Node {
private:
    Node *parent;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;
public:
    Node(Node* _left, Node* _right, Node* _parent);
};

Node::Node(Node* _left, Node* _right, Node* _parent) {
    parent = &_parent;

    //this is where the problem starts
}

我不明白如何指向可能有我想要连接的树的新节点。如果我使用make_unique,我相信会创建一个新节点而不是保留树。

我可能完全错了,因为我刚刚学会了4天前的智能指针(实际上有足够的时间学习一些东西)。

3 个答案:

答案 0 :(得分:5)

首先,可以使用空树,并且默认构造的节点很适合。 在附加节点时将知道父引用,因此,一旦将节点设置为当前树的左子节点,就应更新子节点父节点。

接收unique_ptr可能是个好主意,因为您获得了所接收指针的所有权。以下是一个示例实现:

class Node {
private:
  Node *parent = nullptr;
  std::unique_ptr<Node> m_left;
  std::unique_ptr<Node> m_right;

public:

  void left(std::unique_ptr<Node> child) {
    m_left = std::move(child);
    m_left->parent = this;
  }

  void right(std::unique_ptr<Node> child) {
    m_right = std::move(child);
    m_right->parent = this;
  }
};

您将像以下一样使用它:

int main()
{
  auto tree = std::make_unique<Node>();
  auto subtree = std::make_unique<Node>();

  subtree->right(std::make_unique<Node>());
  tree->right(std::make_unique<Node>());
  tree->left(std::move(subtree));
  return 0;
}

我自己是unique_ptr的新手,希望有人能够进一步纠正我。 BTW不会使用以_开头的名称帽作为您的标识,它们是保留的。

答案 1 :(得分:2)

我认为你不能使用:

Node(Node _left, Node _right, Node _parent);

这将不允许逐个节点构建树节点。相反,使用:

Node(Node* _left, Node* _right, Node* _parent);

这样,您可以使用以下方法创建第一个节点:

Node firstNode(nullptr, nullptr, nullptr);

从那里,您可以构建其他节点。

构建一个简单的树,有三个节点,如下所示

            N1
           /  \
         N2    N3

你可以使用:

Node* N1 = new Node(nullptr, nullptr, nullptr);
Node* N2 = new Node(nullptr, nullptr, N1);
Node* N3 = new Node(nullptr, nullptr, N1);

N1->left = N2;  // Use the equivalent member function.
N1->right = N3;

答案 2 :(得分:0)

我相信你想让父母,左,右孩子公开。至少,这就是我总是使用struct实现节点的方式:

struct Node
{
    Node(std::unique_ptr<Node> _parent = nullptr, 
std::unique_ptr<Node> _left = nullptr, std::unique_ptr<Node> _right = nullptr) : parent(_parent), left(_left), right(_right) {}

    std::unique_ptr<Node> parent;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;

};

如果我错了,请有人纠正我。

相关问题