【发布时间】:2016-05-17 03:53:57
【问题描述】:
我对尝试很陌生。我在网上找到了一些解决方案,但尝试以完全不同的方式定义。我需要这种类型的特里的解决方案。
我需要的是按字母顺序打印 trie 中所有单词的功能。如您所见,插入和搜索功能已完成。这里有2个头文件,是主代码所必需的。
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;
}
【问题讨论】:
-
我将从递归开始。
-
好的,我知道可以使用递归来完成。您是否有更详细的说明?
标签: c++ binary-tree binary-search-tree trie