Trie 树

92 阅读1分钟

Trie 树的本质,就是利用字符串之间的公共前缀,将重复的前缀合并在一起。最后构造出来的就是下面这个图中的样子。

280fbc0bfdef8380fcb632af39e84b32.webp

`

class TrieNode {
  constructor(data){
    this.data = data;
    this.children = new Array(26);
    this.isEndingChar = false
  }
}

class TrieTree {

  constructor(data){
    this.root = new TrieNode('/')
  }

  insert (text) {
    let node = this.root;
    for (let char of text) {
      let index = char.charCodeAt() - 'a'.charCodeAt();
      if(!node.children[index]) {
        node.children[index] = new TrieNode(char);
      }
      node = node.children[index];
    }

    node.isEndingChar = true;
  }

  find (text) {
    let node = this.root;

    for(let char of text) {
      let index = char.charCodeAt() - 'a'.charCodeAt();
      if(node.children[index]) {
        node = node.children[index];
      } else {
        return false;
      }
    }

    return node.isEndingChar;
  }
}

let tree = new TrieTree();
let strs = ["how", "hi", "her", "hello", "so", "see", "he"];
for(let str of strs) {
  tree.insert(str);
}

for(let str of strs) {
  console.log(tree.find(str));
}

console.log(tree.find('he'));

`