如何在其一侧打印二叉树,使输出看起来像这样?
__/a
__/ \b
\ _/c
\_/ \d
\e
(欢迎使用更漂亮的 ascii-art)
这是一些不太有效的代码:
def print_tree(tree):
def emit(node,prefix):
if "sequence" in node:
print "%s%s"%(prefix[:-1],node["name"])
else:
emit(node["left"],"%s_/ "%prefix.replace("/ "," /")[:-1].replace("_"," "))
emit(node["right"],"%s \\ "%prefix.replace("\\ "," \\")[:-1])
emit(tree,"")
哪个输出:
_/hg19
_/ \rheMac2
_/ \mm9
/\_/bosTau4
/ \_/canFam2
_/ \pteVam1
\_/loxAfr3
\dasNov2
范围蔓延:如果您可以传入一个函数,该函数将返回字符串以打印任何节点,那就太好了;这样,我有时也可以打印有关非离开节点的信息。所以一个节点是否有任何东西要打印是由作为参数传入的函数控制的。
这是 JSON 中的一些测试数据:
{
"left": {
"left": {
"left": {
"left": {
"name": "hg19",
"sequence": 0
},
"right": {
"name": "rheMac2",
"sequence": 1
}
},
"right": {
"name": "mm9",
"sequence": 2
}
},
"right": {
"left": {
"name": "bosTau4",
"sequence": 3
},
"right": {
"left": {
"name": "canFam2",
"sequence": 4
},
"right": {
"name": "pteVam1",
"sequence": 5
}
}
}
},
"right": {
"left": {
"name": "loxAfr3",
"sequence": 6
},
"right": {
"name": "dasNov2",
"sequence": 7
}
}
}