문제
요약
- KIWI BANANA
- KIWI APPLE
- APPLE APPLE
- APPLE BANANA KIWI
위와 같은 입력이 주어지면 아래와 같이 출력하자.
APPLE
--APPLE
--BANANA
----KIWI
KIWI
--APPLE
--BANANA
분류
- 트라이
풀이
내 풀이
자식 노드를 딕셔너리(해시 맵)로 관리해주었다.
import sys
input = sys.stdin.readline
n = int(input())
class TrieNode:
def __init__(self, level):
self.level = level
self.children = {}
root = TrieNode(0)
for _ in range(n):
_, *foods = input().rstrip().split()
level = 0
t = root
for food in foods:
level += 1
if food not in t.children:
t.children[food] = TrieNode(level)
t = t.children[food]
def search(node):
l = sorted(node.children.items())
for name, child_node in l:
print("--" * (child_node.level - 1), end="")
print(name)
search(child_node)
search(root)