ENع
→Tries
الدرس 18 · Search trees

Tries: trees of letters

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

The search trees in this module compare whole keys. A trie does something different: it splits each string into letters and stores one letter per level, so words that start the same share a path. Insert cat, car, cart and dog into a real Python trie, look up cart, cap and ca, and list every word that starts with ca. Each node's children live in a Python dict, covered in the Python lesson "Dictionaries and sets" and the Software lesson "Hash maps: finding things by key"; the Software lesson "Trees" covers the basic tree vocabulary.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 18 · تفاعلي
01 / 10

A tree whose links are letters

A trie is a tree for strings. Each node keeps kids, a dict from one letter to a child node, and end, a flag. The root stands for the empty string. Walking down spells a word, one letter per level.

class Node:
    def __init__(self):
        self.kids = {}      # letter -> child Node
        self.end = False    # True if a word ends here

root = Node()        # the empty string ""
child of node p under letter ch = the prefix p + ch
words to store: "cat", "car", "cart", "dog"
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A tree whose links are letters

    A trie is a tree for strings. Each node keeps kids, a dict from one letter to a child node, and end, a flag. The root stands for the empty string. Walking down spells a word, one letter per level.

    class Node:
        def __init__(self):
            self.kids = {}      # letter -> child Node
            self.end = False    # True if a word ends here
    
    root = Node()        # the empty string ""
    child of node p under letter ch = the prefix p + ch
    words to store: "cat", "car", "cart", "dog"
  2. Insert cat: three new nodes

    insert(root, "cat"): the root has no 'c' child, so line 5 makes one, then line 6 steps down to it. Same for 'a' and 't'. Line 7 sets end = True on the last node: the gold dot means a word ends here.

    insert(root, "cat")
      ch = 'c'  not in node.kids -> new Node()  (line 5), step down (line 6)
      ch = 'a'  not in node.kids -> new Node()  (line 5), step down (line 6)
      ch = 't'  not in node.kids -> new Node()  (line 5), step down (line 6)
      node "cat": end = True                  (line 7)
    new nodes: 3, nodes below the root: 3
  3. Insert car: share the prefix

    insert "car": 'c' and 'a' already exist, so line 6 just steps down them. Only 'r' is new. Words that start the same share one path, so the prefix "ca" is stored once.

    insert(root, "car")
      ch = 'c'  already there -> step down      (line 6)
      ch = 'a'  already there -> step down      (line 6)
      ch = 'r'  not in node.kids -> new Node()  (line 5), step down (line 6)
      node "car": end = True                  (line 7)
    new nodes: 1, nodes below the root: 4
  4. Insert cart: car stays a word

    insert "cart": c, a and r all exist; only 't' is new, under "car". The "car" node keeps its gold dot, so both words are stored. An end flag can sit in the middle of a path.

    insert(root, "cart")
      ch = 'c'  already there -> step down      (line 6)
      ch = 'a'  already there -> step down      (line 6)
      ch = 'r'  already there -> step down      (line 6)
      ch = 't'  not in node.kids -> new Node()  (line 5), step down (line 6)
      node "cart": end = True                  (line 7)
    new nodes: 1, nodes below the root: 5
  5. Insert dog: a new branch

    insert "dog": the root has no 'd' child, so a second branch starts at the root: lines 5 and 6 for each letter, line 7 at the end. Four words, 13 letters in total, but only 8 nodes below the root: shared prefixes saved 5.

    insert(root, "dog")
      ch = 'd'  not in node.kids -> new Node()  (line 5), step down (line 6)
      ch = 'o'  not in node.kids -> new Node()  (line 5), step down (line 6)
      ch = 'g'  not in node.kids -> new Node()  (line 5), step down (line 6)
      node "dog": end = True                  (line 7)
    new nodes: 3, nodes below the root: 8
    
    (root)
      c
        a
          t   end
          r   end
            t   end
      d
        o
          g   end
  6. Find cart: one hop per letter

    find(root, "cart") follows one link per letter (line 14): c, a, r, t. 4 hops, and the node it lands on has end = True, so "cart" is stored. The "dog" branch is never looked at.

    find(root, "cart")
      ch = 'c'  in node.kids -> node = "c"  (line 14)
      ch = 'a'  in node.kids -> node = "ca"  (line 14)
      ch = 'r'  in node.kids -> node = "car"  (line 14)
      ch = 't'  in node.kids -> node = "cart"  (line 14)
      return node "cart"                        (line 15)
    search: node is not None and node.end -> True
  7. Find cap: a miss stops early

    find "cap": c and a are there, but the "ca" node has no 'p' child. Line 13 returns None after checking 3 letters. A miss can stop sooner, even at the first letter.

    find(root, "cap")
      ch = 'c'  in node.kids -> node = "c"
      ch = 'a'  in node.kids -> node = "ca"
      ch = 'p'  not in node.kids              (line 12)
      return None                             (line 13)
    node "ca" has kids: 't', 'r'
  8. Find ca: only a prefix

    find "ca" does reach a node, but its end flag is False: "ca" is the start of stored words, not a word itself. So a word search needs both: the node exists and its end is True.

    find(root, "ca") -> node "ca"   (line 15)
    node "ca".end = False
    
    def search(root, word):
        node = find(root, word)
        return node is not None and node.end
    
    search(root, "ca")   -> False
    search(root, "car")  -> True
  9. Every word that starts with ca

    Words starting with "ca": walk to the "ca" node, then visit everything below it. Each gold dot is a word: car, cart, cat. Visiting kids in sorted letter order lists them alphabetically. Autocomplete works this way.

    def words_under(node, prefix):
        if node.end:
            yield prefix
        for ch in sorted(node.kids):
            yield from words_under(node.kids[ch], prefix + ch)
    
    list(words_under(find(root, "ca"), "ca"))
    -> ['car', 'cart', 'cat']
  10. Cost: the length, not the count

    Line 11 loops once per letter: O(L) for a string of length L, however many words are stored. A balanced search tree of n strings needs about log₂ n comparisons instead, and each one may read up to L letters.

    trie: one dict lookup per letter (line 11 loops L times)
      find a string of length L: at most L steps
      a miss can stop at the first letter
    balanced BST of n strings: height about log2 n,
      each comparison reads up to L letters
      n = 1,000,000 words: about 20 comparisons
    price: one node per new letter, a dict in every node

اختبار يتاح بعد الخطوة الأخيرة.