我想遍歷樹數據,將該場景模擬爲自解釋的python腳本。我無法找到爲什麼水平節點不能在遞歸中遍歷。圖遞歸水平(寬度優先)搜索
說明:第一個字符串是腳本中樹的表示形式。 get_childrens
方法是我如何從數據庫獲得響應。
"""
1
11 | 12 | 13
111 112 113 | 121 122 123 |
| 1221 1222 |
"""
# Do not edit this function in the same format getting data
def get_childrens(i):
if i==1: return [11,12,13]
if i==11: return [111,112,113]
if i==12: return [121,122,123]
if i==122: return [1221,1222]
def create_tree(nodeid):
child_users=get_childrens(nodeid)
if child_users:
child_users=[user for user in child_users]
else:
return
return {
"data":{
"type":nodeid
},
"children": [create_tree(e) for e in child_users if create_tree(e)]
}
if __name__=="__main__":
import json
data= create_tree(1)
print json.dumps(data , indent=4)
print "####################### GETTING THIS #####################"
{
"data": {
"type": 1
},
"children": [
{
"data": {
"type": 11
},
"children": []
},
{
"data": {
"type": 12
},
"children": [
{
"data": {
"type": 122
},
"children": []
}
]
}
]
}
print "###################### EXPECTED THIS #####################"
print json.dumps({"data":{"value":1},
"children":[
{"data":{"value":11},
"children":[
{"data":{"value":111},"children":[]},
{"data":{"value":112},"children":[]},
{"data":{"value":113},"children":[]},
],
},
{"data":{"value":12},
"children":[
{"data":{"value":121},"children":[
{"data":{"value":1221},"children":[]},
{"data":{"value":1222},"children":[]},
]},
{"data":{"value":122},"children":[]},
{"data":{"value":123},"children":[]},
],
},
{"data":{"value":13},
"children":[
],
}
]
},indent=4)
我建議你移動給你的Q的編輯 - 這是在適當的爲A.此外,如果我的A幫助,這是很好的做法給予好評,並接受它... –