我正在尝试通过B-Tree实现它来构建c ++中的trie。每个节点都有一个键,一个指向其他节点的指针数组,以及一个布尔值,用于确定它是否为叶子。默认情况下,初始化新节点时所有指针都指向null,每当添加新节点时,前一个节点都指向新节点。
但由于某种原因,我的其他if(currentNode.children [arrayPointer]!= NULL)永远不会被调用。我完全难过了。我不确定是不是因为我标注了错误或者某些事情的顺序不正确。
#include <iostream>
using namespace std;
numberOfWords = 0;
numberOfNodes = 0;
struct Node;
struct Node;
struct Node {
char key;
bool isLeaf;
struct Node *children[36]; //26 letters + 10 digits
};
main() {
//initializing the root
Node root;
root.key ='$';
int i = 0;
while (i < 36) {
root.children[i] = NULL;
i++;
}
root.isLeaf = 1;
numberOfNodes++;
insertWord("the", root);
insertWord("and", root);
insertWord("there", root);
cout << numberOfWords << " words found." << endl;
cout << numberOfNodes << " nodes found." << endl;
}
void insertWord(string word, Node currentNode) {
int wordLength = word.length();
char letterToInsert;
letterToInsert = word[0];
int arrayPointer;
arrayPointer = charToInteger(letterToInsert);
//if the node is not found, a new path is inserted
if (currentNode.children[arrayPointer] == NULL) {
insertNewPath(word, currentNode);
}
//if the node with the current letter is found, I want to recursively call
//insertWord and pass in the updated word and the next node.
//For some reason, this statement is never being called.
else if (currentNode.children[arrayPointer] != NULL) {
string updatedWord;
updatedWord = word.substr(1,wordLength);
Node nextNode;
currentNode.children[arrayPointer] = &nextNode;
insertWord(updatedWord, nextNode);
}
}
//This function will keep recursively calling itself and passing in the new word
//and the new node until the each letter is added.
void insertNewPath(string word, Node currentNode) {
int wordLength;
wordLength = word.length();
if (wordLength > 0) {
char letterToInsert;
letterToInsert = word[0];
int arrayPointer;
//charToInteger takes a character and converts it into an integer value - a=0,b=1,...,8=34,9=35
arrayPointer = charToInteger(letterToInsert);
Node newNode;
numberOfNodes++;
newNode.key = letterToInsert;
// Here, I set the current node's pointer to point to the new node.
// This should cause line 168 to execute when entering an existing
// letter to the trie but for some reason it never does.
currentNode.children[arrayPointer] = &newNode;
//setting every pointer in the new node to null
int i = 0;
while (i < 36) {
newNode.children[i] = NULL;
i++;
}
currentNode.isLeaf = 0;
string updatedWord;
updatedWord = word.substr(1, wordLength);
insertNewPath(updatedWord, newNode);
}
else if (wordLength == 0){
currentNode.isLeaf = 1;
//Once all the letters have been added, the last
//node/letter to be added is set as a leaf, making
//it a complete word.
}
}
我期望得到的输出是
3 words found.
9 nodes found.
相反,我正在
3 words found.
11 nodes found.
因此,为单个字母创建一个节点。