我有一個N-Ary沒有以任何方式排序的樹,每個節點可以有0-N個子節點。鑑於下面的數據結構,假設你有一個TermNode數組,並且該數組是TreeView的第一級,我該如何填充樹視圖?我無法想出一個遞歸的方式來做到這一點。填充樹視圖控件
class TermNode
{
public string Name;
public string Definition;
public List<TermNode> Children
}
我有一個N-Ary沒有以任何方式排序的樹,每個節點可以有0-N個子節點。鑑於下面的數據結構,假設你有一個TermNode數組,並且該數組是TreeView的第一級,我該如何填充樹視圖?我無法想出一個遞歸的方式來做到這一點。填充樹視圖控件
class TermNode
{
public string Name;
public string Definition;
public List<TermNode> Children
}
感謝所有我是越來越糊塗了,因爲我不知道,對於一個給定的樹節點TN,tn.Nodes.Add會返回添加樹節點 一旦你知道該解決方案是直線前進,像這樣
private void /*TreeNode*/ RecursiveAdd(OntologyNode on, TreeNode tn)
{
if (on.Children.Count == 0)
{
return;
}
foreach (OntologyNode child in on.Children)
{
TreeNode tCur = tn.Nodes.Add(child.Name);
tCur.Tag = child;//optional for some selected node events
RecursiveAdd(child, tCur);
}
}
,並開始遞歸調用
foreach(OntologyNode on in Nodes)
{
if (on.IsTopLevelNode == true)// internal not pertinent to this code snippet
{
TreeNode tn = tvOntoBrowser.Nodes.Add(on.Name);
tn.Tag = on;
if (on.Children.Count > 0)
{
RecursiveAdd(on, tn);
}
}
}
這裏有一段代碼讓你開始遞歸。這不是測試(我現在不能),但你應該得到的想法:
public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)
{
foreach (TermNode n in TermNodeList)
{
TreeNode CurrentNode = Parent.Add(n.Name);
// no need to recurse on empty list
if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);
}
}
// initial call
List<TermNode> AllTermNodes = /* all your nodes at root level */;
BuildTreeView(treeView1.Nodes, AllTermNodes);
剛掏出仿製藥的旋..工作很好。值得一看...
public interface INode<T>
{
List<T> Children { get; }
}
class TermNode:INode<TermNode>
{
public string Name;
public string Definition;
public List<TermNode> Children { get; set; }
public TermNode()
{
this.Children = new List<TermNode>();
}
}
public class TreeBuilder<T> where T : INode<T>
{
public Func<T, TreeNode> obCreateNodeFunc;
public void AddNode(TreeView obTreeView, T obNodeToAdd, TreeNode obParentNodeIfAny)
{
TreeNodeCollection obNodes;
if (obParentNodeIfAny == null)
{
obNodes = obTreeView.Nodes;
}
else
{
obNodes = obParentNodeIfAny.Nodes;
}
int iNewNodeIndex = obNodes.Add(obCreateNodeFunc(obNodeToAdd));
TreeNode obNewNode = obNodes[iNewNodeIndex];
foreach (T child in obNodeToAdd.Children)
{
AddNode(obTreeView, child, obNewNode);
}
}
}
// calling code - Some class
static TreeNode GetTreeNodeFor(TermNode t)
{
return new TreeNode(t.Name); // or any logic that returns corr TreeNode for T
}
void Main()...
{
TermNode[] arrNodesList;
// populate list with nodes
TreeBuilder<TermNode> tb = new TreeBuilder<TermNode>();
tb.obCreateNodeFunc = GetTreeNodeFor;
foreach (TermNode obNode in arrNodesList)
{
tb.AddNode(treeView, obNode, null);
}
}