In computer science, a trie, or prefix tree, is an ordered tree data structure that is used to store an associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key it is associated with. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Values are normally not associated with every node, only with leaves and some inner nodes that correspond to keys of interest.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
/*data to be save*/ | |
def data | |
/*child nodes of this node*/ | |
def children = [:] | |
} | |
class Trie { | |
/*root node with empty data*/ | |
def root = new Node(data:'') | |
def insert(key) { | |
def node = root | |
key.each { | |
/*find the relevant child node*/ | |
def child = node.children[it] | |
/*if child does not exist, creates it*/ | |
if (child == null) { | |
child = node.children[it] = new Node(data:it) | |
} | |
node = child | |
} | |
} | |
def search(key) { | |
def node = root | |
def x = key.find { | |
node = node.children[it] | |
/*if the child does not exist, key does not exist in trie*/ | |
node == null | |
} | |
return x == null | |
} | |
} | |
def t = new Trie() | |
t.insert("trie") | |
t.insert("tree") | |
t.insert("i") | |
t.insert("it") | |
t.insert("ite") | |
assert true == t.search("t") | |
assert true == t.search("tr") | |
assert true == t.search("tri") | |
assert true == t.search("trie") | |
assert true == t.search("tre") | |
assert true == t.search("tree") | |
assert true == t.search("i") | |
assert true == t.search("it") | |
assert true == t.search("ite") | |
assert false == t.search("triex") | |
assert false == t.search("treexx") | |
assert false == t.search("ix") |
No comments:
Post a Comment