I cant complete this

Tell us what’s happening:

Your code so far


var displayTree = tree => console.log(JSON.stringify(tree, null, 2));
var Node = function () {
this.keys = new Map();
this.end = false;
this.setEnd = function () {
    this.end = true;
};
this.isEnd = function () {
    return this.end;
};
};
var Trie = function () {
// Only change code below this line
this.root = new Node()
this.add = function (word) {
    let node = this.root
    for (let i = 0; i < word.length; i++) {
        let letter = word[i]
        if (node.keys[letter]) {
            node = node.keys[letter]
        } else {
            let newNode = new Node()
            node.keys[letter] = newNode
            node = newNode
        }
    }
    node.setEnd()
}
this.print = function () {
    let node = this.root
    let holder = []
    for (let key in node.keys) {
        console.log(key, "key")
        holder.push(node.keys[key])
    }
    console.log(holder, "=holder")

    let recurse = (root) => {
        if (root.end === true) {
            console.log('reace')
        } else {

        }
    }
    recurse(node)
}
this.isWord = function (word) {
    let node = this.root
    for (let i = 0; i < word.length; i++) {
        let letter = word[i]
        if (node.keys[letter]) {
            node = node.keys[letter]
            if (i === word.length - 1) {
                if (node.end === false) {
                    return false
                }
            }
        } else {
            return false;
        }
    }
    return true
}
// Only change code above this line
};

let myDictionary = new Trie()
myDictionary.add('jump');
myDictionary.add('jumps');
myDictionary.add('jumped');
myDictionary.add('house');
myDictionary.add('mouse');
displayTree(myDictionary)

myDictionary.print()

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36.

Challenge: Create a Trie Search Tree

Link to the challenge:

1 Like

I completed the print() function recursively like you are trying to do. You’ll need to iterate over the set of keys for each node inside the recursive function, and for each key, recur over the nodes of the key. I also used two other arrays as helpers; one for pushing and popping letters of the prefix (the list of nodes up to current; I think that is your intent with holder) and one for storing words, which I found like you have started to do by looking for the end marker and pushing the prefix to the word list. You’ll also need to return your word list from the function.

You are close to the solution already; I’m sure you’ll get there. Good luck.

1 Like