Untitled

 avatar
unknown
plain_text
2 years ago
1.0 kB
12
Indexable
#include <iostream>
using namespace std;


// trie class 

class Node {
public:
	
	char data;
	unordered_map<char, Node *> m;
	bool isWordEnding; // is this node a word ending node
	
	Node(char d){
		data = d;
		isWordEnding = false;
	}
	
};

// class trie
OOP - Good code

class Trie{

private:
	Node * root;
public:
	// default constructor
	Trie(){
		root = new Node('\0');
	}
	
	// inserting a word in the trie
	void insert(string word){
		
		Node * temp = root;
		
		for(char ch: word){
			
			// check if this character is already present in the node
			if(temp->m.count(ch) == 0){
				Node * n = new Node(ch);
				temp->m[ch] = n;
			}
			temp = temp->m[ch]; // temp is going to be updated everytime
		}
		
		temp->isWordEnding = true;
		
	}
	
	bool search(string word){
		
		Node * temp = root;
		
		for(char ch : word){
			
			if(temp->m.count(ch) == 0){
				return false;
			}
			
			temp = temp->m[ch];
		}
		
		return temp->isWordEnding;
	}
	
	
}



int main() {
	// your code goes here
	
	cout << "hello";
	return 0;
}
Editor is loading...