2017-10-09 87 views
1

我遍歷非二叉樹,我有一個函數來計算節點的高度和孩子的數量。我想要做的是我的節點的孩子通過高度的第一排序,每個高組裏面,我希望它通過兒童的數量進行排序Python樹遍歷和排序排序列表中的項目組

如:

 a 
/ \ 
    b  c 
/|\ /
d e f g 
    /
     h 

所以當我遍歷樹:

def orderTree(node):   
    if "children" in node: 
     if node['children']: 
      node['children'].sort(key=findHeight) 
      node['children'].sort(key=countChildren) 

      for child in node['children']: 
       print(child['name']) 
       orderTree(child) 

與此代碼我去=> A,C,G,H,b,d,E,F 但我需要的是=> A,b,d,E,F,C,G ,h

任何想法如何對排序的項目組進行排序IDE的Python列表?

回答

0

你想要做的就是所謂的「多字段排序」是什麼,

要通過自己的身高由它們的數量排序的節點列表,然後孩子乾脆放棄sort以下功能key

lambda x : (findHeight(x), children(x)) 

這只是回報是一個(身高,孩子)的元組。然後sort使用這個元組來比較兩個節點。

代碼:

def orderTree(node): 
    # I combined the two ifs 
    if "children" in node and node['children']: 
     node['children'].sort(key= lambda x : (findHeight(x), children(x))) 

     for child in node['children']: 
      print(child['name']) 
      orderTree(child) 

可以說我有 A = (a,b)B = (x, y)

這兩個元會這樣進行比較:

def compare_tuple(A, B): 
    if A[0] != B[0]: return A[0] < B[0] 
    else: return A[1] < B[1]