Trie树
import scala.collection.mutable.{ArrayBuffer, Map} class TrieTree { private var root: TrieNode = new TrieNode() def insert(word: String) { var (text, node) = (word.trim, root) text.foreach( c => node = node.children.getOrElseUpdate(c, new TrieNode()) ) node.terminable = true node.count += 1 } def find(word: String): Boolean = { var node = root word.foreach ( c => { if (!node.children.contains(c)) return false node = node.children(c) }) node.terminable } def delete(word: String) { if (!find(word)) return deleteText(word, root) } private def deleteText(word: String, node: TrieNode): Boolean = { if (word.length == 0) { node.terminable = false return node.children.isEmpty } if (deleteText(word.substring(1), node.children(word.charAt(0).toChar))) { node.children -= word.charAt(0).toChar if (node.children.isEmpty && node.terminable == false) true } false } def traverse(): Unit = traverseTrie(root, new StringBuffer()) private def traverseTrie(node: TrieNode, word: StringBuffer) { if (node.terminable) { println(word + "------" + node.count) if (node.children.isEmpty) return } val children = node.children.keySet children foreach { c => traverseTrie(node.children(c), word.append(c)) word.deleteCharAt(word.length() - 1) } } class TrieNode { var terminable = false var count = 0 var children: Map[Char, TrieNode] = Map[Char, TrieNode]() } } object TrieTree { def main(args: Array[String]) { val trie = new TrieTree()
trie.insert("abcd") trie.insert("cd") trie.insert("abdr") trie.traverse() trie.delete("cd") println("\n" + trie.find("cd")) } }