../ Algorithm Templates
-rw-r--r--aguang1.2 KiB1 min read

modified

Trie Data Structure

Trie is a kind of preffix search tree, by which we can map strings to any data type. For any given string ss, the time complexity of seeking is O(∣s∣)O(|s|).

Here is an example of trie structure with 4 strings (her, say, she, shy) inserted.

empty empty h h empty->h h s s empty->s s he he h->he e her her he->her r sa sa s->sa a sh sh s->sh h say say sa->say y she she sh->she e shy shy sh->shy y

Implementation

c++
#include <queue>
#include <set>
#include <map>
#include <string>

using namespace std;

template<typename T>
class trie {

  public:

    struct node {

      node *parent;
      
      map<char, node*> children;

      T ext;
    };

  private:
    
    node *_root = new node({ .parent = NULL });

  public:

    node *root() {

      return _root;
    }

    node& operator[](const string &key) {

      node *ptr = root();

      for (const char &c : key) {

        if (NULL == ptr->children[c]) {

          ptr->children[c] = new node({ .parent = ptr });
        }

        ptr = ptr->children[c];
      }

      return *ptr;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window