Skip to main content
CSData StructuresDiagramIntermediate

Trie (Prefix Tree)

KO: 트라이 (접두사 트리)·EN: Trie (Prefix Tree)·JA: トライ木

A tree data structure sharing common string prefixes along paths, enabling O(L) prefix search and autocomplete independent of dictionary size

Table of Contents

Structure Diagram

Trie (Prefix Tree) Shared Character PathTap a node
cdatroRoot ("")'c''d''a''t' (cat …'r' (car …'o' (do ✓)
ROOTRoot ("")
2 links
Quick Answer

What is Trie (Prefix Tree)?

A tree data structure sharing common string prefixes along paths, enabling O(L) prefix search and autocomplete independent of dictionary size. It is a core concept in Data Structures within CS.

Core Principles

A Trie (Prefix Tree) stores strings character by character so that words sharing a common prefix share the same path from the root.

  • O(L) Lookup: Searching or checking prefix existence depends only on the query length L, not on the total number of stored words N.
  • No Hash Collisions & Lexicographical Order: Branching directly on characters avoids hashing overhead and supports ordered enumeration via DFS.
  • Memory Trade-off: Naive fixed-size child arrays per node can consume significant memory on sparse or Unicode alphabets.

Practical Takeaways

  • Compress into a Radix Tree: Merging single-child chains into one edge (Radix/Patricia Trie) slashes memory footprint and powers production routers.
  • Choose child representation wisely: Use fixed arrays for small ASCII/bit alphabets, or hash maps / sorted slices for Unicode text.
  • Precompute Top-K suggestions: Caching top-ranked completions at prefix nodes avoids expensive subtree traversals on every keystroke.

Notable Examples

  • Search Autocomplete & Spellcheck: Instant prefix suggestions as users type.
  • IP Routing (Longest Prefix Match): Matching CIDR prefixes bit-by-bit in network routers.
  • HTTP Routers: Frameworks like Gin, Go httprouter, and Fastify matching URL routes via Radix Tries.