# tree - preorder
tree = [('a', [('b', [('d', []),
('e', [])]),
('c', [('f', [])])])]
def preorder(tree):
stack = [tree[0]]
output = []
while stack:
value, children = stack.pop()
output.append(value)
stack.extend(reversed(children))
return output
print(preorder(tree))
# 결과
['a', 'b', 'd', 'e', 'c', 'f']
# tree - preorder
tree = [('a', [('b', [('d', []),
('e', [])]),
('c', [('f', [])])])]
from collections import deque
def levelorder(tree):
queue = deque([tree[0]])
output = []
while queue:
value, children = queue.popleft()
output.append(value)
queue.extend(children)
return output
print(levelorder(tree))
# 결과
['a', 'b', 'c', 'd', 'e', 'f']
댓글 영역