# Trie

```cpp

#include <iostream>
#include <vector>
#include <string>
using namespace std;

const int ALPHABET_SIZE = 26;

// trie node
class TrieNode
{
	public:
		vector<TrieNode*> children;

		bool isEndOfWord;                 // true means that the node represents end of a word

		TrieNode(){
		    children.resize(ALPHABET_SIZE);
		}
};


// Returns new trie node (with all children initialized to NULLs)
TrieNode* createNewNode() {
	TrieNode *node = new TrieNode();

	node->isEndOfWord = false;

	for (int i = 0; i < ALPHABET_SIZE; i++){
		node->children[i] = NULL;
	}

	return node;
}


// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(TrieNode* root, string key)
{
	TrieNode *itr = root;

	for (int i = 0; i < key.length(); i++)
	{
		int index = key[i] - 'a';
		if (!itr->children[index]){
		    TrieNode* newNode = createNewNode();
			itr->children[index] = newNode;
		}

		itr = itr->children[index];
	}

	// mark last node as leaf
	itr->isEndOfWord = true;
}


bool search(TrieNode* root, string key)
{
	TrieNode* itr = root;
 
	for (int i = 0; i < key.length(); i++)
	{
		int index = key[i] - 'a';
		
		if (!itr->children[index]){
			return false;
		}

		itr = itr->children[index];
	}

	return (itr->isEndOfWord);
}

// Driver
int main()
{
	// Input keys (use only 'a' through 'z' and lower case)
	vector<string> keys = {"the", "a", "there", "answer", "any", "by", "bye", "their" };
	
	int n = keys.size();

	TrieNode *root = createNewNode();

	// Construct trie
	for (int i = 0; i < n; i++){
		insert(root, keys[i]);
	}

	// Search for different keys
	cout << "the :: "  << search(root, "the")     << endl;
	cout << "these :: " << search(root, "these")  << endl;
	cout << "their :: " << search(root, "their")  << endl;
	cout << "thaw :: " << search(root, "thaw")    << endl;
	
	
	return 0;
}



```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.gomchik.com/tech/c++/trie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
