function TreeNode(val) {
this.key = val;
this.cnt = 1;
this.isEnd = false;
this.value = null;
this.children = new Map();
}
function Tree() {
this.root = new TreeNode(null);
}
Tree.prototype = {
insert(str, value) {
let node = this.root, len = str.length;
for (let i = 0; i < len; i++) {
key = str[i];
if (node.children[key] === undefined) {
node.children[key] = new TreeNode(key);
} else {
node.children[key].cnt++;
}
node = node.children[key];
}
node.value = value;
node.isEnd = true;
},
query(str) {
let node = this.root, len = str.length;
for (let i = 0; i < len; i++) {
let key = str[i];
if (node.children[key] === undefined) {
return false;
} else {
node = node.children[key];
}
}
return node.isEnd ? node.value : false;
},
delete(str) {
if (this.query(str) === false) {
console.log('不存在要删除的字符串');
return;
}
let node = this.root, len = str.length;
for (let i = 0; i < len; i++) {
let key = str[i];
if (node.children[key] === undefined) {
return;
} else {
node.children[key].cnt--;
if (!node.children[key].cnt) {
delete node.children[key];
return;
}
}
node = node.children[key];
}
}
}
let tree = new Tree();
tree.insert('111');
tree.insert('121');
tree.insert('112');
tree.delete("112");
let fs = require('fs');
fs.writeFile('./test.json', JSON.stringify(tree), err => {
});
{
"root": {
"key": null,
"cnt": 1,
"isEnd": false,
"value": null,
"children": {
"1": {
"key": "1",
"cnt": 2,
"isEnd": false,
"value": null,
"children": {
"1": {
"key": "1",
"cnt": 2,
"isEnd": false,
"value": null,
"children": {
"1": {
"key": "1",
"cnt": 1,
"isEnd": true,
"children": {}
},
"2": {
"key": "2",
"cnt": 1,
"isEnd": true,
"children": {}
}
}
}
}
}
}
}
}