Table of contents | |
Introduction | |
What is a Trie? | |
Key Features of Tries | |
Trie Implementation in C++: | |
Sample Problems |
Code Example 1: TrieNode Class Implementation
class TrieNode {
public:
bool isEndOfWord;
TrieNode* children[26]; // Assuming only lowercase alphabets
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
Explanation:
Code Example 2: Trie Class Implementation
class Trie {
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(const string& word) {
TrieNode* curr = root;
for (char c : word) {
int index = c - 'a';
if (curr->children[index] == nullptr) {
curr->children[index] = new TrieNode();
}
curr = curr->children[index];
}
curr->isEndOfWord = true;
}
bool search(const string& word) {
TrieNode* curr = root;
for (char c : word) {
int index = c - 'a';
if (curr->children[index] == nullptr) {
return false;
}
curr = curr->children[index];
}
return curr->isEndOfWord;
}
};
Explanation:
Sample Usage:
Trie trie;
// Inserting words into the Trie
trie.insert("apple");
trie.insert("banana");
trie.insert("orange");
// Searching for words in the Trie
cout << trie.search("apple") << endl; // Output: 1 (true)
cout << trie.search("banana") << endl; // Output: 1 (true)
cout << trie.search("grape") << endl; // Output: 0 (false)
Explanation:
In the sample usage, we create a Trie object and insert three words: "apple," "banana," and "orange."
We then perform search operations to check if specific words exist in the Trie using the 'search' function.
Problem 1: Implement a function to count the number of words starting with a given prefix in a given Trie.
Problem 2: Given a list of words, find the longest common prefix among them.
Problem 3: Implement a function to remove a word from a Trie.
Note: For the solutions to the sample problems, refer to the accompanying code samples and explanations.
By following the concepts and examples presented in this article, you can gain a solid understanding of Tries and their implementation in C++.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|