js实现字典树

 

 

 

复制代码
//字典树和链表的区别,是node.next指向一个node 或 node[]的区别
function Node(){
   this.next=[];
    this.value= null;
}

function TrieST(){
    this.root = new Node();
    
    this.put = (key,value)=>{
       _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);
        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; } //当前字符 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; } //如果当前值是要的值,返回 if(i == key.length){ return x; } let c = key.charAt(i); return _get(x.next[c],key,i+1); } }

let tries= new TrieST(); 
tries.put(
"heheh",10);
console.log(tries)

//...
复制代码

 

posted @   Esther_Cheung  阅读(294)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示