functiondeleteNode(data) { if (this.search(data)) { // 判断是否存在该单词(字符串) for (let i inthis.root.children) { if (this.deleteNext(this.root, i, data, data)) { return; } } } returnthis; }
/** * @param parent 父节点 * @param index 子节点在父节点children数组中的索引位置 * @param stringData 递归遍历中的字符串 * @param delStr 调用delete方法时的原始字符串 */ functiondeleteNext(parent, index, stringData, delStr) { let node = parent.children[index]; // 若字符与节点key不相等,则不匹配 if (stringData[0] != node.key) { returnfalse; } else { // 若与key相等,继续判断 let children = node.children; if (children.length == 0 && stringData.length == 1) { // 叶子节点,最后一个字符,则完全匹配 // 删除叶子节点,利用父节点删除子节点原理 parent.children.splice(index, 1); // 字符串从尾部移除一个字符后,继续遍历删除方法 this.deleteNode(delStr.substring(0, delStr.length - 1)); } elseif (children.length > 0 && stringData.length > 1) { // 既不是叶子节点,也不是最后一个字符,则继续递归查找 for (let i in children) { if (children[i].key == stringData[1]) { returnthis.deleteNext(node, i, stringData.substring(1), delStr); // 记得return 递归函数,否则获取的返回值为undefined } } } } }
functioninsertData(data, node){ if (data === '') { return; }
let children = node.children; let haveData = null; for (let i in children) { if (children[i].key == data[0]) { haveData = children[i]; } } if(haveData) { this.insertData(data.substring(1), haveData); }else{ if(children.length === 0) { let insertNode = new TrieNode(data[0]); children.push(insertNode); this.insertData(data.substring(1), insertNode); }else{ let validPosition = 0; for (let j in children) { if (children[j].key < data[0]) { validPosition++; } } let insertNode = new TrieNode(data[0]); children.splice(validPosition, 0, insertNode); this.insertData(data.substring(1), insertNode); } } }
functionsearch (data) { if (data === '' || this.root.children.length === 0) { returnfalse; } for (let i inthis.root.children) { if (this.searchNext(this.root.children[i], data)) { returntrue; } } returnfalse; }
functiondeleteNode(data) { if (this.search(data)) { for (let i inthis.root.children) { if (this.deleteNext(this.root, i, data, data)) { return; } } } returnthis; }
functiondeleteNext(parent, index, stringData, delStr) { let node = parent.children[index]; if (stringData[0] != node.key) { returnfalse; } else { let children = node.children; if (children.length == 0 && stringData.length == 1) { parent.children.splice(index, 1); this.deleteNode(delStr.substring(0, delStr.length - 1)); } elseif (children.length > 0 && stringData.length > 1) { for (let i in children) { if (children[i].key == stringData[1]) { returnthis.deleteNext(node, i, stringData.substring(1), delStr); } } } } }
functionprint () { for (let i inthis.root.children) { this.nodeNumber++; this.printHelper(this.root.children[i], [this.root.children[i].key]); } }
functionprintHelper (node, data) { if (node.children.length === 0) { console.log('>', data.join('')); return; } for (let i in node.children) { this.nodeNumber++; data.push(node.children[i].key); this.printHelper(node.children[i], data); data.pop(); } }