Introduction to Trie (Prefix Tree)
A Trie is a tree-like data structure that is used for efficiently storing and searching strings, especially in applications like autocomplete, spell checking, and IP routing.
Key Properties of a Trie:
- Nodes: Each node represents a character.
- Root: The root node is empty and serves as the starting point.
- Children: Each node has up to 26 children (for lowercase English letters) or more, depending on the character set.
- End-of-Word Marker: Some nodes are marked to indicate the end of a word.
Basic Trie Operations:
1. Insertion
Inserting a word involves traversing the trie and creating new nodes for characters that don’t exist.
2. Search
Search checks whether a word exists in the trie by traversing its nodes.
3. Prefix Search
This checks whether any word in the trie starts with a given prefix.
Implementation of Basic Trie in JavaScript:
class TrieNode { constructor() { this.children = {}; // Stores child nodes this.isEndOfWord = false; // Marks the end of a word } } class Trie { constructor() { this.root = new TrieNode(); } // Insert a word insert(word) { let node = this.root; for (let char of word) { if (!node.children[char]) { node.children[char] = new TrieNode(); } node = node.children[char]; } node.isEndOfWord = true; // Mark the end of the word } // Search for a word search(word) { let node = this.root; for (let char of word) { if (!node.children[char]) { return false; } node = node.children[char]; } return node.isEndOfWord; } // Check if any word starts with the given prefix startsWith(prefix) { let node = this.root; for (let char of prefix) { if (!node.children[char]) { return false; } node = node.children[char]; } return true; } } // Example usage const trie = new Trie(); trie.insert("apple"); console.log(trie.search("apple")); // true console.log(trie.search("app")); // false console.log(trie.startsWith("app")); // true trie.insert("app"); console.log(trie.search("app")); // true
Advanced Trie Operations:
1. Delete a Word:
Deleting a word involves a recursive approach, where we remove nodes that are no longer needed.
delete(word, node = this.root, depth = 0) { if (depth === word.length) { if (!node.isEndOfWord) return false; // Word doesn't exist node.isEndOfWord = false; return Object.keys(node.children).length === 0; // Check if node has children } const char = word[depth]; if (!node.children[char]) return false; const shouldDeleteChild = this.delete(word, node.children[char], depth + 1); if (shouldDeleteChild) { delete node.children[char]; return Object.keys(node.children).length === 0 && !node.isEndOfWord; } return false; }
2. Count Words with a Prefix:
Count how many words start with a given prefix.
countWordsWithPrefix(prefix) { let node = this.root; for (let char of prefix) { if (!node.children[char]) return 0; node = node.children[char]; } return this._countWords(node); } _countWords(node) { let count = node.isEndOfWord ? 1 : 0; for (let char in node.children) { count += this._countWords(node.children[char]); } return count; }
3. Autocomplete Suggestions:
Given a prefix, return all words that start with it.
getWordsWithPrefix(prefix) { let node = this.root; for (let char of prefix) { if (!node.children[char]) return []; node = node.children[char]; } return this._collectWords(node, prefix); } _collectWords(node, prefix) { let results = []; if (node.isEndOfWord) results.push(prefix); for (let char in node.children) { results = results.concat(this._collectWords(node.children[char], prefix + char)); } return results; }
Time Complexity:
- Insert: O(L) (L = length of the word)
- Search: O(L)
- Prefix Search: O(L)
- Delete: O(L)
Applications of Trie:
- Autocomplete Systems (e.g., search bars, text editors).
- Spell Checkers.
- IP Routing (longest prefix matching).
- Word Games (e.g., Boggle).
- DNA Sequence Matching.
The above is the detailed content of Introduction to Trie (Prefix Tree). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
