Python树遍历和排序排序列表中的项目组
问题描述:
我遍历非二叉树,我有一个函数来计算节点的高度和孩子的数量。我想要做的是我的节点的孩子通过高度的第一排序,每个高组里面,我希望它通过儿童的数量进行排序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列表?
答
你想要做的就是所谓的“多字段排序”是什么,
要通过自己的身高由它们的数量排序的节点列表,然后孩子干脆放弃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]
答
您之后树遍历的类型称为预订。不知道完整的结构很难理解你的代码。但它看起来像是先从根节点查看子节点然后遍历。
我想你想打开第一个子节点,然后继续遍历。对于预购,应该是这样的。
node
node.left
node.right
这是一个很好的参考 http://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/