首页
学习
活动
专区
圈层
工具
发布

python 二叉树迭代器

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

代码语言:javascript
复制
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))

代码语言:javascript
复制
for ch in root.depth_first():
    print(ch)
# Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
下一篇
举报
领券