-
Notifications
You must be signed in to change notification settings - Fork 8
/
BottomupTrie
90 lines (79 loc) · 2.17 KB
/
BottomupTrie
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// CPP program to traverse in bottom up manner
#include <bits/stdc++.h>
using namespace std;
#define CHILDREN 26
#define MAX 100
// Trie node
struct trie {
trie* child[CHILDREN];
// endOfWord is true if the node represents
// end of a word
bool endOfWord;
};
// Function will return the new node(initialized to NULLs)
trie* createNode()
{
trie* temp = new trie();
temp->endOfWord = false;
for (int i = 0; i < CHILDREN; i++) {
// Initialise all child to the null, initially
temp->child[i] = NULL;
}
// Return newly created node
return temp;
}
// Function will insert the string in a trie recursively
void insertRecursively(trie* itr, string str, int i)
{
if (i < str.length()) {
int index = str[i] - 'a';
if (itr->child[index] == NULL) {
// Assining a newly created node
itr->child[index] = createNode();
}
// Recursive call for insertion
// of a string in a trie
insertRecursively(itr->child[index], str, i + 1);
}
else {
// Make the endOfWord true which represents
// the end of string
itr->endOfWord = true;
}
}
// Function call to insert a string
void insert(trie* itr, string str)
{
// Function call with necessary arguments
insertRecursively(itr, str, 0);
}
// Function to print traverse
// the tree in bottum to top manner
void printPattern(trie* itr)
{
// Base condition
if (itr == NULL)
return;
// Loop for printing t a value of character
for (int i = 0; i < CHILDREN; i++) {
// Recursive call for print pattern
printPattern(itr->child[i]);
if (itr->child[i] != NULL) {
char ch = (i + 97);
cout << ch << ", "; // Print character
}
}
}
// Driver code
int main()
{
trie* root = createNode();
// Function to insert a string
insert(root, "thier");
insert(root, "there");
insert(root, "answer");
insert(root, "any");
// Function call for printing a pattern
printPattern(root);
return 0;
}