js实现字典树

房东的猫 提交于 2020-02-29 09:48:18
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);

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!