创建n叉树

use*_*084 0 c++ tree vector

我正在尝试创建一个带有子向量的 n 叉树。

这是我到目前为止所得到的。

在node.h文件中我有这个:

  #include <vector>
  #include <string>

  using namespace std;

  class Node{

  private:
      Node *parent; 
      vector <Node*> children; 

      int data; 

  public: 
      Node();
      Node(Node parent, vector<Node> children);
      Node(Node parent, vector<Node> children, int data);

      Node * GetParent(); 

      void SetChildren(vector<Node> children);
      vector<Node>* GetChildren();
      void AddChildren(Node children);

      void SetData(int data);
      int GetData();

      bool IsLeaf();
      bool IsInternalNode();
      bool IsRoot();

  };
Run Code Online (Sandbox Code Playgroud)

这是我的node.cpp 文件。

   #include "node.h"

   Node::Node(){
       this->parent = NULL; 
       this->children = NULL; 
       this->data = 0;
   }

   Node::Node(Node parent, vector<Node> children){
       this->parent = &parent; 
       this->children = &children; 
   }

   Node::Node(Node parent, vector<Node> children, int data){
       this->parent = &parent; 
       this->children = &children; 
       this->data = data; 
   }

   Node* Node:: GetParent(){
       return this->parent;
   }

   void Node::SetChildren(vector<Node> children){
       this->children = &children; 
   }

   vector<Node> * Node::GetChildren(){
       return this->children;
   }

   void Node::AddChildren(Node children){
       this->children.push_back(children);
   }

   void Node::SetData(int data){
       this->data = data;
   }
Run Code Online (Sandbox Code Playgroud)

这显然是行不通的。我的主要问题是我不太确定如何处理孩子们的向量。我在网上看了一些教程后写了这篇文章,但正如你所看到的,我非常困惑。

zak*_*ter 5

代码中的主要(也可能是唯一)问题是您将Node类定义为通过指针 ( ) 操作节点Node*

class Node{
  private: 
    Node *parent; 
    vector <Node*> children;
Run Code Online (Sandbox Code Playgroud)

但是你的方法是通过值(Node)来操作节点。

例如,在构造函数中:

Node::Node(Node parent, vector<Node> children){
    this->parent = &parent;
Run Code Online (Sandbox Code Playgroud)

存储父参数的地址是行不通的,它是一个临时对象,您需要将 a 传递Node* parent给构造函数或创建一个新的Node对象。

    this->children = &children; 
Run Code Online (Sandbox Code Playgroud)

这没有任何意义,因为this->children是 的向量Node*并且children参数是 的向量Node。同样,您需要将 的向量传递Node*给构造函数或创建新的节点对象。

SetChildren您在和中有同样的问题AddChildren

另外,由于您将节点作为指针进行操作,因此要非常小心内存管理。C++ 中没有垃圾收集器,您必须在适当的时间处理delete所有事情。new