-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie (String).cpp
More file actions
57 lines (52 loc) · 1.2 KB
/
Copy pathTrie (String).cpp
File metadata and controls
57 lines (52 loc) · 1.2 KB
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
struct Trie_Node{
int terminal;
Trie_Node *child[26];
int cnt;
};
Trie_Node* init(){
Trie_Node* node=new Trie_Node;
node->cnt=0;
node->terminal=0;
for (int i = 0; i < 26; ++i){
node->child[i]= nullptr;
}
return node;
}
void insert(Trie_Node*root,string &s){
Trie_Node*temp=root;
for (int i = 0; s[i]; ++i){
int ind=(s[i]-'a');
if(temp->child[ind]== nullptr){
temp->child[ind]=init();
}
temp=temp->child[ind];
temp->cnt++;
if(s[i+1]=='\0'){
temp->terminal++;
}
}
}
int sum(Trie_Node*root,string &s){
Trie_Node*temp=root;
int ans = 0;
for (int i = 0; s[i]; ++i){
int ind=(s[i]-'a');
temp = temp->child[ind];
ans += temp->cnt;
}
return ans;
}
void getAllStrings(Trie_Node*curr,string &curr_word,bool &found){
if(curr== nullptr)return;
if(curr->terminal>0){
cout<<curr_word<<"\n";
found=true;
}
for (int i = 0; i < 26; ++i){
if(curr->child[i]==nullptr)continue;
char ch=i;
curr_word.push_back(ch);
getAllStrings(curr->child[i],curr_word,found);
curr_word.pop_back();
}
}