用Javascript实现Trie树的代码(即前缀树)

来源:互联网 发布:中邮网络培训学院官网 编辑:程序博客网 时间:2024/06/15 03:50
<!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>
原创粉丝点击