如何编写表示非二叉树的级别顺序的代码?

时间:2016-03-12 21:05:29

标签: python python-3.x recursion tree

这里t表示一棵树。树可以有一个孩子的列表。 act是一种行为,例如print。我的代码显示了根t以下所有级别的正确顺序。如何修改代码以包含t本身?

def levelorder_visit(t, act):
    """
    Visit every node in Tree t in level order and act on the node
    as you visit it.

    @param Tree t: tree to visit in level order
    @param (Tree)->Any act: function to execute during visit

    >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3)
    >>> def act(node): print(node.value)
    >>> levelorder_visit(t, act)
    0
    1
    2
    3
    4
    5
    6
    7
    """
    if t:
        for x in t.children:
            act(x)
        for i in t.children:
            levelorder_visit(i,act)
    ###prints out "1,2,3,4,5,6,7" for the above docstring example

1 个答案:

答案 0 :(得分:0)

您可以创建一个levelorder遍历列表,然后对它们进行操作。

def levelorder_visit(t):
    children = []
    if t:
        children.extend(t.children)
        for ch in t.children:
            children.extend(levelorder_visit(ch))
    return children

def act_traversed(root):
  nodes = [root]
  nodes.extend(levelorder_visit(root))
  for n in nodes: 
    act(n)

act_traversed(n)