【问题标题】:Python tree traversal and sorting groups of items inside sorted listPython树遍历和排序列表中的项目组
【发布时间】:2017-10-09 20:50:37
【问题描述】:

我正在遍历非二叉树,我有一个函数来计算节点的高度和子节点的数量。我想做的是首先按高度对节点的子节点进行排序,然后在每个高度组中按子节点数对其进行排序

例如:

      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

知道如何对 python 列表中的已排序项目组进行排序吗?

【问题讨论】:

    标签: python algorithm sorting data-structures tree


    【解决方案1】:

    你要做的叫做“多字段排序”,

    要按节点的高度和子节点的数量对节点列表进行排序,只需将以下函数作为keysort

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

    这只是返回一个 (height, children) 的元组。然后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]
    

    【讨论】:

      【解决方案2】:

      您所追求的树遍历类型称为预购。如果不知道完整的结构,就很难理解你的代码。但看起来您首先从根节点查看子节点,然后向下遍历。

      我认为您想打开第一个子节点,然后继续遍历它。对于预购,它应该是这样的。

      node
      node.left
      node.right
      

      这是一个很好的参考 http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        • 2020-01-07
        • 1970-01-01
        相关资源
        最近更新 更多