Friday, February 10, 2012

Trie: Second Implementation in Groovy

This is another version of Trie implementation in my previous post. The new one comes with a flag to identify a complete word.

2 comments:

  1. using groovy collections.. all of it can fit in less than 10 lines

    class Node {
    Node(data){this.data=data}
    def data /*data to be save*/
    def children = [:] /*child nodes of this node*/
    }

    class Trie {
    def root = new Node( '') /*root node with empty data*/
    def insert(key) { key?.inject(root) { node, v -> node.children[v]?:(node.children[v] = new Node (v))} }
    def search(key) { key?.inject(root) { node, v -> node.children[v]} } / returns last node for the key or null
    }

    ReplyDelete