这个怎么样:def printTree(parent, tree, indent=''):
print parent
if parent not in tree:
return
for child in tree[parent][:-1]:
sys.stdout.write(indent + '|-')
printTree(child, tree, indent + '| ')
child = tree[parent][-1]
sys.stdout.write(indent + '`-')
printTree(child, tree, indent + ' ')
tree = {
0 : [0, 4],
4 : [360],
272 : [3460],
368 : [4184],
472 : [504, 576, 7016],
568 : [584, 640],
576 : [664, 672],
640 : [1048],
664 : [368, 372, 512, 788],
788 : [2120, 2720, 2976, 2996, 3956, 3980]
}
printTree(472, tree)
printTree(472, tree)
472
|-504
|-576
| |-664
| | |-368
| | | `-4184
| | |-372
| | |-512
| | `-788
| | |-2120
| | |-2720
| | |-2976
| | |-2996
| | |-3956
| | `-3980
| `-672
`-7016
也许你喜欢这样,我不知道。在
它没有为递归内置任何检查,因此如果您在0上尝试它,它将陷入无休止的递归(最终由于堆栈溢出而中止)。您可以通过传递已处理节点的跟踪来检查递归。在
这也找不到您的森林中的树根列表,所以您也必须这样做。(但这听起来像是另一个问题。)