2016-03-12 45 views
0

这里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 

回答

0

您可以创建级别顺序遍历列表,然后对它们进行操作。

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) 
+0

对不起,我认为你的代码是预先订购的。 – 1412

+0

对不起,没有想到这一点。查看更正的代码。 – Muctadir