Trie Implementation

Trie Implementation

Tree Node has three attributes:

  • Character
  • boolean to check isLeaf
  • children map
Insert Algorithm
  1. Take root children
  2. Iterate all characters of given string
    1. Set current_character = string.charAt(i)
    2. If current_character not exist in children map then
      1. Create a trie node for current_character and add to children map
    3. Get trieNode from children map for current_character
    4. If current_character is last character in given string then
      1. Set trieNode.isLeaf = true
    5. Set children = trieNode.children
Search Node Algorithm
  1. Get children of root
  2. Set trieNode = null
  3. Iterate all characters of given string
    1. Set current_character = string.charAt(i)
    2. If current_character not exist in children map then
      1. return null
    3. Else
      1. Set trieNode = children.get(current_character)
    4. Set children = trieNode.children
  4. Return trieNode

Latest Source Code:
Github: Trie.java


Output:

Is prefix "hrishi"  exist? true
Is "hrishik" exist? false
Is "hrishikesh" exist? true
Is "kumar" exist? false
Author: Hrishikesh Mishra