解题思路:
注意事项:
参考代码:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
def insert_word(root, word):
node = root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def count_nodes(node):
count = 1 # 当前节点算一个节点
for child in node.children.values():
count += count_nodes(child)
return count
# 构建字典树
root = TrieNode()
# 读取输入
words = []
while True:
try:
word = input().strip()
if word == "":
break
words.append(word)
except EOFError:
break
# 插入单词到字典树
for word in words:
insert_word(root, word)
# 计算节点数
node_count = count_nodes(root)
# 输出结果
print(node_count)
0.0分
0 人评分