考虑到我在MongoDB中有一棵树,如图所示。
我想做的是按特定顺序获取节点后代。
def descendants(nodeID):
descendants = []
stack = []
item = vt.comments.find_one({'_id': nodeID })
stack.append(item)
stack.sort(key=lambda x: x['order'])
while(len(stack) > 0):
currentNode = stack.pop()
children = vt.comments.find({'parent': currentNode["_id"] })
for child in children:
descendants.append(child['_id'])
stack.append(child)
stack.sort(key=lambda x: x['order'])
print(descendants)
我的程序与此类似,当我调用此函数时
像这样descendants(0)
它的输出类似于:
[1,2,3,12,13,14,15,8,9,10,11,4,5,6,7,16,17,18,19]
但我想做的是按此顺序访问项目:
[1,4,5,6,7,2,8,9,10,11,3,12,16,17,18,19,13,14,15]
答案 0 :(得分:0)
这是例外情况:
def descendants(nodeID):
descendants = []
stack = []
item = vt.comments.find_one({'_id': nodeID })
stack.append(item)
stack.sort(key=lambda x: x['order'], reverse=True)
while(len(stack) > 0):
currentNode = stack.pop()
descendants.append(child['_id'])
children = vt.comments.find({'parent': currentNode["_id"] })
for child in children:
stack.append(child)
stack.sort(key=lambda x: x['order'], reverse=True)
print(descendants)