js实现字典树

function Node(){
   this.next=[]
    this.value= ''
}
//字典树和链表的区别,是next指向一个node 和 node[]的区别
function RTree(){ this.root = new Node(); this.put = (key,value)=>{ return _put(this.root, key ,value,0) } this.get = (key)=>{ let res = _get(this.root, key, 0) if(res === null || res === undefined){ return null} return res.value } this.contains = (key)=>{ let res = this.get(key) console.log('get 返回了',res) if(res !== null && res !== undefined ){ return true } return false } function _put (x,key,val,i) { //如果不存在,初始化 if(x=== null || x === undefined){ x = new Node(); } //如果找到了,更新或者写入它储存的值 if(i== key.length){ x.value = val return x } //get字符 let c = key.charAt(i) //设定在X.next中,key[i]的值 x.next[c] =_put(x.next[c],key,val,i+1) //返回key[i]对应的Node到树中 return x; } function _get (x,key,i) { if(x=== null || x === undefined){ return null } console.log("key is " ,key) //如果当前值是要的值,返回 if(i == key.length){ return x; } let c = key.charAt(i) return _get(x.next[c],key,i+1) } } let tree = new RTree() tree.put("heheh",0);

猜你喜欢

转载自www.cnblogs.com/xinfangzhang/p/12381499.html
今日推荐