[Algorithm] Trie data structure
For example we have an array of words:
[car, done, try, cat, trie, do]
What is the best data structure to store the data and easy for search?
We can use Trie data structure, it is a tree, but not a binary tree. The reuslts of constructing a tree by using the example array data.
True of False means whether this letter is the last of the word.
We can code it by Javascript:
- We are using Map data structure
- If there is no existing node for giving letter, we create a new Node.
- If there is a existing node, then we continue to next letter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | function Node() { return { keys: new Map(), isWord: false }; } function BuildTrie() { const root = new Node(); return { root, add(word, node = this .root) { if (word.length === 0) { node.isWord = true ; return ; } const [head, ...rest] = word; if (!node.keys.has(head)) { node.keys. set (head, new Node()); } return this .add(rest, node.keys. get (head)); }, hasWord(word, node = this .root) { if (!word) { return false ; } while (word.length > 1) { if (!node.keys.has(word[0])) { return false ; } else { node = node.keys. get (word[0]); word = word.substr(1); } } return node.keys.has(word) && node.keys. get (word).isWord; }, print() { let words = []; function search(node = this .root, string = "" ) { if (node.keys.size != 0) { for ( let letter of node.keys.keys()) { search(node.keys. get (letter), string .concat(letter)); } if (node.isWord) { words.push( string ); } } else { string .length > 0 ? words.push( string ) : undefined; } } search( this .root, "" ); return words.length > 0 ? words : null ; } }; } const t = new BuildTrie(); t.add( "cat" ); t.add( "cal" ); console.log(t.hasWord( "cat" )); // true console.log(t.hasWord( "catt" )); // false |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-03-17 [Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE
2017-03-17 [TypeScript] Using ES6 and ESNext with TypeScript
2016-03-17 [AngularJS] Angular 1.5 multiple transclude
2016-03-17 [RxJS] Creating Observable From Scratch
2015-03-17 [AngularJS] Introduction to angular-formly