python 二叉树迭代器

  • 2019 年 10 月 10 日
  • 筆記

class Node: def init(self, value): self._value = value self._children = []

def __repr__(self):      return 'Node({!r})'.format(self._value)    def add_child(self, node):      self._children.append(node)    def __iter__(self):      return iter(self._children)    def depth_first(self):      yield self      for c in self:          yield from c.depth_first()

Example

if name == 'main': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) child1.add_child(Node(3)) child1.add_child(Node(4)) child2.add_child(Node(5))

for ch in root.depth_first():      print(ch)  # Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)