I wrote a program to find all possible words with a list of given letters in a ternary search tree. The output is a sorted set of all words. Following is the python code for finding the words:
def _find_words(self, node: Node, letters: str, buffer=''):
if node is None:
return
for c in letters:
if node.key < c:
self._find_words(node.high, letters, '')
elif node.key > c:
self._find_words(node.low, letters, '')
else:
buffer += node.key
if node.isEnd:
self.words.add(buffer)
self._find_words(node.equal,
letters.replace(node.key, '', 1), buffer)
The tree contains the following words: cat, acts, act, actor, at, bug, cats, up, actors, upper
I get the following output for the letters 'abugpscort':
['acts', 'cats', 'cat', 'act', 'bug', 'ors', 'up', 'or', 't']
whereas the output should be:
['actors', 'actor', 'acts', 'cats', 'cat', 'act', 'bug', 'up', 'at']
How can I fix this?