Skip to content

Instantly share code, notes, and snippets.

@maxkibble
Created May 16, 2018 07:18
Show Gist options
  • Select an option

  • Save maxkibble/4e5fc4415cfefb187034b5b4bfa3e996 to your computer and use it in GitHub Desktop.

Select an option

Save maxkibble/4e5fc4415cfefb187034b5b4bfa3e996 to your computer and use it in GitHub Desktop.
Trie
struct TrieNode {
int minVal;
TrieNode *child[2];
TrieNode() {
minVal = inf;
child[0] = child[1] = NULL;
}
};
struct Trie {
TrieNode *root;
void insert(int val) {
int bits[maxd], v = val;
for (int i = 0; i < maxd; i++) {
bits[maxd - 1 - i] = (v & 1);
v >>= 1;
}
if (root == NULL) root = new TrieNode();
TrieNode *fa = root, *cur = NULL;
for (int i = 0; i < maxd; i++) {
if (fa->child[bits[i]] == NULL) {
fa->child[bits[i]] = new TrieNode();
}
cur = fa->child[bits[i]];
cur->minVal = std::min(cur->minVal, val);
fa = cur;
}
}
void deleteTrie(TrieNode *cur) {
if (cur == NULL) return;
deleteTrie(cur->child[0]);
deleteTrie(cur->child[1]);
delete cur;
}
} trie;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment