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 }
using groovy collections.. all of it can fit in less than 10 lines
ReplyDeleteclass 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
}
http://www.tutesfree.com/
ReplyDelete