Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- from operator import attrgetter
- class Node:
- def __init__(self, name):
- self.children = []
- self.name = name
- def addChild(self, child):
- self.children.append(child)
- def __repr__(self):
- return "Node('{}')".format(self.name)
- def iter_traverse(node, attribute="children"):
- seen = set()
- stack = deque([node])
- result = []
- getter = attrgetter(attribute)
- while stack:
- node = stack.popleft()
- node_id = id(node)
- if node_id not in seen:
- seen.add(node_id)
- result.append(node)
- children = getter(result[-1])
- for child in children:
- stack.append(child)
- return result
- node1 = Node("one")
- node2 = Node("two")
- node3 = Node("three")
- [node3.addChild(Node("N{}".format(x))) for x in range(5)]
- node4 = Node("four")
- node1.addChild(node2)
- node2.addChild(node3)
- node3.addChild(node4)
- node3.addChild(node1) # CYCLE!
- print(iter_traverse(node1))
- # [Node('one'), Node('two'), Node('three'), Node('N0'), Node('N1'), Node('N2'), Node('N3'), Node('N4'), Node('four')]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement