1. 程式人生 > >用Javascript實現Trie樹的程式碼(即字首樹)

用Javascript實現Trie樹的程式碼(即字首樹)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function TrieNode(key) {
        this.key = key;
        this.son = [];
    }
    function Trie() {
        this.root = new TrieNode
(null); } Trie.prototype = { insertData: function (stringData) { this.insert(stringData, this.root); }, insert: function (stringData, node) { if (stringData == '') { return; } var son = this.getSon(node); var
haveData = null; for (var i in son) { if (son[i].key == stringData[0]) { haveData = son[i]; } } if (haveData) { this.insert(stringData.substring(1), haveData);//說明找到了對應的元素,那如果沒有找到了? } else { if
(son.length == 0) { //當前沒有子元素,所以應該判斷一下 var node = new TrieNode(stringData[0]); son.push(node); this.insert(stringData.substring(1), node);//對吧,此時應該將該元素插入子元素中 } else {//當前子元素的長度不為零,需要查詢一個合適的位置去插入元素 var validPosition = 0; for (var j in son) { if (son[j].key < stringData[0]) { validPosition++; } } var node = new TrieNode(stringData[0]); son.splice(validPosition, 0, node); this.insert(stringData.substring(1), node);//對吧,此時應該將該元素插入子元素中 } } }, delete: function (stringData) { }, query: function (stringData) { }, getSon: function (node) { return node.son; } , printdata1: function (node,data) { if (node.son.length==0){ console.log('ddddd',data.join('')); return; } for (var i in node.son) { data.push(node.son[i].key); this.printdata1(node.son[i],data); data.pop(); } }, printData: function () { for (var i in this.root.son){ this.printdata1(this.root.son[i],[this.root.son[i].key]); } }, isExit:function (node,queryData) { if (node.key==queryData[0]){ } } }; var trie = new Trie(); trie.insertData('in'); trie.insertData('inn'); trie.insertData('ten'); trie.insertData('ted'); trie.insertData('tea'); trie.insertData('to'); trie.printData(); </script> </body> </html>