1. 程式人生 > >python實現連結串列的深度優先遍歷

python實現連結串列的深度優先遍歷

在《python cookbook》(簡稱python奇技淫巧書)中看到的,覺得太簡潔了,遂記錄下來:

class Node(object):

    def __init__(self, value):
        self._value = value
        self._children = []

    # 新增子元素
    def add_children(self, value):
        self._children.append(value)

    def __iter__(self):
        return iter(self._children)

    def
__repr__(self):
return 'Node:{}'.format(self._value) # 深度優先遍歷演算法,用了生成器的原理 def deep_first(self): yield self for ch in self: yield from ch.deep_first() root = Node(0) child1 = Node(1) child2 = Node(2) root.add_children(child1) root.add_children(child2) child1.add_children(Node(5
)) child1.add_children(Node(6)) child2.add_children(Node(4)) for ch in root.deep_first(): print(ch)

這裡寫圖片描述