2014-12-30 50 views
0

我想遍歷樹數據,將該場景模擬爲自解釋的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) 

回答

2

隨着

[create_tree(e) for e in child_users if create_tree(e)] 

你商討消除誰不反過來有孩子的兒童。因此,例如"data":{"value":1}只會以子女1112結束,這些子女本身確實有一些子女,但不是13,這並不是。

我懷疑這是錯誤的邏輯,而是你的意思是,而更像

[create_tree(e) or e for e in child_users] 
0

感謝亞歷克斯,返回,而不是空的解決了這個問題的數據。

def create_tree(nodeid): 
    child_users=get_childrens(nodeid) 
    if child_users: 
     child_users=[user for user in child_users] 
    else: 
     return { 
       "data":{ 

       "type":nodeid 
       }, 
       "children": [] 
      } 

    return { 
       "data":{ 

       "type":nodeid 
       }, 
       "children": [create_tree(e) or e for e in child_users] 
      } 
+1

我建議你移動給你的Q的編輯 - 這是在適當的爲A.此外,如果我的A幫助,這是很好的做法給予好評,並接受它... –