From 4653a735eea6f950d800ccf99b823ad7f859f74c Mon Sep 17 00:00:00 2001 From: Vip2016-0 Date: Wed, 5 Oct 2022 18:49:54 +0530 Subject: [PATCH] Implement_Trie --- CPP/Tries/implementTrie.cpp | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 CPP/Tries/implementTrie.cpp diff --git a/CPP/Tries/implementTrie.cpp b/CPP/Tries/implementTrie.cpp new file mode 100644 index 00000000..f2d99eee --- /dev/null +++ b/CPP/Tries/implementTrie.cpp @@ -0,0 +1,55 @@ +class Node { +public: + char c; + Node* child[26]; + bool isWord; + + Node(char c) { + this -> c = c; + isWord = false; + + for(int i = 0 ; i < 26 ; i++) + child[i] = NULL; + } +}; + +class Trie { + Node* root; + Node* getNode(string &s){ + Node* curr = root; + for(auto &ch:s){ + if(curr -> child[ch - 97] == NULL) + return NULL; + curr = curr -> child[ch - 97]; + } + + return curr; + } +public: + Trie() { + root = new Node('\0'); + } + + void insert(string word) { + Node* curr = root; + + for(auto &ch:word){ + if(curr -> child[ch - 97] == NULL) + curr -> child[ch - 97] = new Node(ch); + curr = curr -> child[ch - 97]; + } + + curr -> isWord = true; + } + + bool search(string word) { + Node* reqNode = getNode(word); + + return reqNode && reqNode -> isWord; + } + + bool startsWith(string prefix) { + return getNode(prefix) != NULL; + } +}; +