Рекурсивная функция дает ошибку сегментации, как указать объект-указатель на его дочерний элемент? - PullRequest
0 голосов
/ 24 октября 2019

Итак, у меня есть объект prefixtree с несколькими узлами. Каждый узел состоит из символа, является ли он конечным узлом, и его дочерние элементы хранятся в массиве указателей объектов (до 26 значений). Мне нужно напечатать слова, найденные под данным узлом.

Пример ниже.

 a
/ \
b  c
    \
     t

Если функция вызывается на узле с символом 'a', она должна напечатать ab и действовать. Я планирую сделать это, добавив к строке, пока не достигну узла, помеченного как окончательный, а затем удалив эту букву. Я хочу реализовать рекурсивную функцию, но при установке узла на дочерний узел этого узла я получаю ошибку сегментации.

void PrefixTreeNode::printAllWords() const
{
  PrefixTreeNode* node; 

  for(char i = 'a'; i < 'a' + ALPHABET_SIZE; i++)
  {
    if(getChild(i) != nullptr)
    {
      if(!isFinal())
      {
        nodeList.push_back(i);
        cout << "added: " << i << endl;
        node = node->getChild(i);    //this line results to segmentation fault
        node->printAllWords();       //How would I call the function on the node's child?
      }
      else if(isFinal()) 
      {
        nodeList.push_back(i);
        cout << nodeList;
        nodeList.pop_back();
        return;
      }
    }
  }
}

Получить дочернюю функцию:

PrefixTreeNode* PrefixTreeNode::getChild(char c)
{
  if (isalpha(c))
    return link[tolower(c)-'a'];
  else
    return nullptr;
}

const PrefixTreeNode* PrefixTreeNode::getChild(char c) const
{
  if (isalpha(c))
    return link[tolower(c)-'a'];
  else
    return nullptr;
}

Узел Объект:

class PrefixTreeNode
{
  friend PrefixTree;
private:
  char c;
  bool final;
  PrefixTreeNode* link[ALPHABET_SIZE];
public:
  //Constructs a new node
  PrefixTreeNode();
  //Copy constructor
  PrefixTreeNode(const PrefixTreeNode&);
  //Copy assignment
  const PrefixTreeNode& operator=(const PrefixTreeNode&);
  //Returns the character this node contains
  char getChar() const { return c; }
  //Returns whether this node is the end of a word
  bool isFinal() const { return final; }
  //Changes whether this node is the end of a word
  void setFinal(bool b) { final = b; }
  //Returns the node corresponding to the given character
  PrefixTreeNode* getChild(char);
  //Returns the node corresponding to the given character
  const PrefixTreeNode* getChild(char) const;
  //Adds a child corresponding to the given character
  void addChild(char);
  //Removes the child corresponding to the given character
  void deleteChild(char);
  //TODO:  print all words that end at or below this PrefixTreeNode
  void printAllWords() const;
  //Destructor
  ~PrefixTreeNode();
};

1 Ответ

0 голосов
/ 24 октября 2019

Если я просто скажу вам, почему строка вызвана ошибкой сегмента, я могу сказать, что вы можете инициализировать узел переменной над строкой.

Я не мог знать весь код, но я рекомендуюизмените это, как это.

void PrefixTreeNode::printAllWords() const
{
  for(char i = 'a'; i < 'a' + ALPHABET_SIZE; i++)
  {
    PrefixTreeNode* node = getChild(i); 
    //if(getChild(i) != nullptr)
    if(node != nullptr)
    {
      nodeList.push_back(i);//this line will be run, ALWAYS whatever the return of isFinal, so I moved it to here.
      if(!isFinal())
      {
        //nodeList.push_back(i); //moved to the front of 'if'
        cout << "added: " << i << endl;
        //just remove it
        //node = node->getChild(i);    //this line results to segmentation fault
        node->printAllWords();       //How would I call the function on the node's child?
      }
      //else if(isFinal()) //duplicated
      else
      {
        //nodeList.push_back(i); //moved to the front of 'if'
        cout << nodeList; //I don't know the type of nodeList, but you may take care of it.
        nodeList.pop_back();
        return;
      }
    }
  }
}

...