[英]Building tree view algorithm
我正在尋找用於從記錄創建樹形視圖的最佳和最快算法。
我的數據庫中有這樣的記錄:
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: []
}
]
}]
我嘗試遞歸地執行此操作,但是我的解決方案不夠理想。
問候
通常,您可以通過三個步驟執行此操作:
首先,按parent排序列表。
接下來,創建這些結構的哈希圖(字典),並按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);
此時,您將擁有一個包含所有頂級項目的字典。 但是帶有孩子的節點也將它們填充。 然后,您可以通過遍歷字典並僅輸出父級為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("}");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.