2016-03-12 61 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