티스토리 뷰

Python

Tree

techbard 2016.06.12 10:25




# 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']


댓글
댓글쓰기 폼
공지사항
Total
407,537
Today
11
Yesterday
19
«   2019/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
글 보관함