JS:调试基于Map的trie树

时间:2018-03-22 15:21:26

标签: javascript dictionary tree trie

我使用JS Map实现了Trie树。 每个条目都是TrieBlock,定义如下:

class TrieBlock {
  constructor (key) {
    this.related = new Map() // children (key => UID) 
    this.key = key // node key in Trie
    this.eof = false // end-of-word stop flag
    this.data = null // additional embeded data, associated with a word
  }


}

// and the Trie
class Trie {
  constructor(debug) {
    this.debug = debug
    this.entries = new Map()
    this.entries.set(null, new TrieBlock()) // Trie ROOT block

  }

  insert(str, withData) {
    // ... ok for me !
  }

  has(word) {
    // walk through Trie
    // seek for the word
  }

  fetch(word) {
    // fetch the data associated with the word
  }
}    

为什么要在地图中展平特里?只是为了简化序列化过程。好吧,存储UID的成本过高:这些是8位十六进制UID(比如'a2b4c6d8'),但是我希望它可以加快速度,因为Map是时间常数的复杂性。

我的问题是:如何打印所有前缀以进行调试?我尝试使用DFS(深度优先搜索)算法,但这很棘手

类似的东西:

trie.insert('CAR', 'Vroom!')  
trie.inseert('CAST', 'Habracadabra')
trie.inseert('CAR', 'Meow!')

可能会输出:

* ROOT
    . C
      . A
        . R : Vroom!
        . S
          . T : Habracadra!
        . T : Meow!

编辑:

通过在控制台中运行:

$ node dist/test-debug.js 

当dist / test-debug.js为:

var ecmasy = require('ecmasy');

trie = new e cmasy.Trie();

trie.insert('DESCAT');
trie.insert('DESCAMP');
trie.insert('DESTOOP');

console.log('' + trie);

我们获得了类似的东西:

ecmasy/Trie:

 0 : null  false
 * 1 : D  false
 * * 2 : E  false
  * * * 3 : S  false
 * * * * 4 : C  false
 * * * * 4 : T  false
 * * * * * 5 : A  false
 * * * * * 5 : O  false
 * * * * * * 6 : T  true
 * * * * * * 6 : M  false
 * * * * * * 6 : O  false
 * * * * * * * 7 : P  true
 * * * * * * * 7 : P  true

堆栈长度,符号和foef标志值为。

但更恰当的答案是:

D
+ D
  + S
    + C
      + A
        +M
          +P
        +T
         +O
           +O
             +P        

编辑:(2)

我将尽快提供一个序列化算法,该算法需要使用自定义回调函数运行,以序列化用户定义的数据。

有什么建议吗?谢谢你的到来。

1 个答案:

答案 0 :(得分:0)

使用coorect DFS:

 after inserting "DESTOOP", "DESCAT", "LYS" and "DESCAMP" strings :

 : null  false
  : D  false
   : E  false
    : S  false
     : C  false
      : A  false
       : M  false
        : P  true
       : T  true
     : T  false
     : O  false
       : O  false
        : P  true
  : L  false
   : Y  false
    : S  true

这个DFS提供了正确的输出,比如打开的文件夹树窗口,但是在控制台中。在repo github中提交> hefeust> ecmasy早点来。

享受你的下午!