Tries Flashcards
1
Q
Trie
A
- Tree-based data structure
- Used to implements sets or maps
- Each node in the tree is a letter in the key
- Each node stores an array of pointers to all possible letters in key
- If keys are words, each node stores alphabet array
- If keys are numbers, each node stores 10-digit array
- Value of each node is value (in key/val pair) or flag indicating membership (in set)
- All operations a O(k), length of the word
2
Q
Trie
Implementation
A
- Implemented with nodes and pointers
- Each node stores:
- an array of pointers
- an isComplete flag
- Root’s isComplete flag doesn’t mean anything
3
Q
Trie
Remove
A
- Implemented recursively
- Finds the word, and then deletes nodes while backtracking
Steps
- Create pointer to letter in word, starting at -1 (because you start at root)
- Check if progress through word equals length of word
- If so..
- Check if word is present in trie
- If so, check number of children (loop through array pointers)
- If no kids, return true delete bool
- If not, increment pointer in word
- Check if child node exists
- Perform remove on child node
- If del bool == true, delete pointer to child
- If node is a word, or has additional children, set del bool to false
- Return del bool
Complexity
Time
Best ⇔ Average ⇔ Worst: O(k)
Space
O(1)
* k is the length of the longest word
4
Q
Trie
Print in Order
A
- Use pre-order traversal to print in lexographical order
5
Q
Trie
Insert
A
- Loop through each letter in word
- Find child based on index of letter in array
- Create new child nodes as neccessary
- Exit loop, set isComplete flag to true