2016-12-27 72 views
0

我正在尋找從記錄中創建樹視圖的最佳和最快的算法。構建樹視圖算法

我在我的數據庫中的記錄是這樣的:

ID|name|parent 
1 Foo 0 
2 Boo 1 
3 Coo 1 
4 Goo 2 

我想收到的結構是:

[{ 
    name: Foo 
    children: [ 
     { 
      name: Boo 
      children: [ 
       { 
        name: Goo 
        children: [] 
       } 
      ] 
     }, 
     { 
      name: Coo 
      children: [] 
     } 
    ] 
}] 

我試圖遞歸做到這一點,但是我怕我的解決辦法是不夠優化。通過

首先,排序列表:

問候

+0

一些數據庫sql語句有層次支持,遞歸查詢。否則,你可能會使用(在SQL中)一個祖先表'(id,ancestor_id,steps)'來確定父母的父母。 –

+0

使用父排序比使用排隊構建樹視圖 –

回答

0

通常你在三個步驟做到這一點。

接下來,創建一個由ID索引的這些結構的哈希映射(字典)。那就是:

class Node 
{ 
    int Id; 
    string Name; 
    int Parent; 
    List<node> Children; 
} 

(。我只是用一個C類僞代碼你必須轉化爲你使用任何語言)

然後,經過列表順序。對於每個節點,將其添加到字典中,並將其添加到父節點。那就是:

for each item in list 
    newNode = CreateNewNode(id, name, parent); 
    dictionary.Add(id, newNode); 
    if (parent != 0) 
     dictionary[parent].Children.Add(newNode); 

此時你有一個包含了所有在頂層的項目的字典。但有孩子的節點也讓他們居住。然後,您可以輸出您的TreeView通過遍歷字典,只輸出那些有0的父項節點:

// Output initial stuff here 
// and then output all top-level nodes 
for each node in dictionary 
    if (node.Parent == 0) 
    { 
     outputNode(node, 0); 
    } 
// Output closing braces here 

而且outputNode是遞歸的:

outputNode(Node node, int level) 
{ 
    // here, compute indentation based on level. 
    // you'll want to put that indentation before every output line 
    writeLine("{"); 
    writeLine("name:", node.Name); 
    writeLine("children: ["); 
    for each child in children 
     outputNode(child, level+1); 
    writeLine("]"); 
    writeLine("}"); 
}