Я довольно новичок в попытках. Я нашел некоторые решения в сети, но попытки определяются совершенно по-другому. Мне нужно решение для этого типа trie.Распечатать все слова в алфавитном порядке от trie
Мне нужна функция печати всех слов из trie в алфавитном порядке. Как видите, выполняются функции «Вставка» и «Поиск». Вот два файла заголовков, необходимых для основного кода.
EntryType.h
#include <iostream>
using namespace std;
const int MAXLENGTH = 10;
class EntryType
{
public:
EntryType();
EntryType(char * key);
EntryType(EntryType & entry);
~EntryType();
bool operator== (const EntryType& item) const;
bool operator!= (const EntryType& item) const;
friend istream& operator>> (istream& is, EntryType& item);
friend ostream& operator<< (ostream& os, EntryType item);
void EntryKey(char word[]);
void PrintWord();
private:
char entryKey[MAXLENGTH];
};
ostream& operator<< (ostream& os, EntryType item)
{
os << item.entryKey;
return os;
}
EntryType::EntryType()
{
// empty instance constructor
}
EntryType::~EntryType()
{
// destructor
}
void EntryType::EntryKey(char word[])
{
for (int i = 0; i < 10; i++)
{
entryKey[i] = word[i];
}
}
void EntryType::PrintWord()
{
cout << entryKey << endl;
}
TrieType.h
#include <iostream>
#include <string>
#include "EntryType.h"
const int LETTERS = 26;
typedef char Key[MAXLENGTH];
struct Trienode
{
Trienode *branch[LETTERS];
EntryType *ref;
};
class TrieType
{
private:
Trienode * root;
public:
TrieType();
~TrieType();
TrieType(TrieType &originalTree);
void operator=(TrieType & originalTree);
void MakeEmpty();
void InsertTrie(Key newkey, EntryType *newentry);
EntryType * TrieSearch(Key target);
bool DeleteTrie(Key delkey);
void PrintTrie();
};
TrieType::TrieType()
{
root = NULL;
}
TrieType::~TrieType()
{
// destructor
}
TrieType::TrieType(TrieType &originalTree)
{
// constructor
}
EntryType *TrieType::TrieSearch(Key target)
{
int i;
Trienode * current = root;
for (i = 0; i < MAXLENGTH && current; i++)
if (target[i] == '\0')
break;
else
current =
current->branch[target[i] - 'a'];
if (!current)
return NULL;
else
if (!current->ref)
return NULL;
return current->ref;
}
Trienode *CreateNode()
{
int ch;
Trienode *newnode = new Trienode;
for (ch = 0; ch < LETTERS; ch++)
newnode->branch[ch] = NULL;
newnode->ref = NULL;
return newnode;
}
void TrieType::InsertTrie(Key newkey, EntryType *newentry)
{
int i;
Trienode *current;
if (!root)
root = CreateNode();
current = root;
for (i = 0; i < MAXLENGTH; i++)
if (newkey[i] == '\0')
break;
else
{
if (!current->branch[newkey[i] - 'a'])
current->branch[newkey[i] - 'a'] = CreateNode();
current = current->branch[newkey[i] - 'a'];
}
if (current->ref != NULL)
cout << "\nTried to insert a duplicate key." << endl;
else
current->ref = newentry;
}
Я бы начал с рекурсии. – drescherjm
Хорошо, я знаю, что это можно сделать с помощью рекурсии. Возможно, у вас есть какие-то более близкие инструкции? – vlada