
怎样用一个List 创建树 25
我现在有个结构,{name,fatherName}.在List里放着很多这样的结构。fatherName=null时直接加到treeview上。怎样把List里的结构加到...
我现在有个结构, { name, fatherName}. 在List里放着很多这样的结构。 fatherName = null时 直接加到 treeview 上。 怎样把List 里的结构加到treeview上呢。fatherName = null的节点可能不只一个。
感谢各位大虾,帮我尽快解决下 展开
感谢各位大虾,帮我尽快解决下 展开
2个回答
展开全部
你这种树的存储结构叫双亲链表表示法,只不过在这里是线性结构.我做了一个Winforms例子,list内的结构是String[]类型.先拖一个TreeView
private List<string[]> listTree = new List<string[]>();
private void Form1_Load(object sender, EventArgs e)
{
listTree.Add(new string[] { "a", null });//初始化List
listTree.Add(new string[] { "b", "a" });
listTree.Add(new string[] { "c", "a" });
listTree.Add(new string[] { "d", "c" });
listTree.Add(new string[] { "e", "c" });
listTree.Add(new string[] { "f", null });
listTree.Add(new string[] { "g", null });
listTree.Add(new string[] { "h", "f" });
listTree.Add(new string[] { "i", "f" });
CreateTree(null, GetList(listTree, null));//创建树
}
private List<string[]> GetList(List<string[]> list, string s)//此方法寻找子节点集合
{
List<string[]> temp=new List<string[]>();
foreach (string[] li in list)
{
if (li[1]==s)
{
temp.Add(li);
}
}
return temp;
}
private void CreateTree(TreeNode node, List<string []> list)//递归创建树
{
if (list.Count > 0)
{
foreach (string [] li in list)
{
TreeNode n = new TreeNode();
n.Text = li[0].ToString();
if (li[1]==null)//如果为null直接加到树上
this.treeView1.Nodes.Add(n);
else
node.Nodes.Add(n);
CreateTree(n, GetList(listTree, li[0]));
}
}
}
private List<string[]> listTree = new List<string[]>();
private void Form1_Load(object sender, EventArgs e)
{
listTree.Add(new string[] { "a", null });//初始化List
listTree.Add(new string[] { "b", "a" });
listTree.Add(new string[] { "c", "a" });
listTree.Add(new string[] { "d", "c" });
listTree.Add(new string[] { "e", "c" });
listTree.Add(new string[] { "f", null });
listTree.Add(new string[] { "g", null });
listTree.Add(new string[] { "h", "f" });
listTree.Add(new string[] { "i", "f" });
CreateTree(null, GetList(listTree, null));//创建树
}
private List<string[]> GetList(List<string[]> list, string s)//此方法寻找子节点集合
{
List<string[]> temp=new List<string[]>();
foreach (string[] li in list)
{
if (li[1]==s)
{
temp.Add(li);
}
}
return temp;
}
private void CreateTree(TreeNode node, List<string []> list)//递归创建树
{
if (list.Count > 0)
{
foreach (string [] li in list)
{
TreeNode n = new TreeNode();
n.Text = li[0].ToString();
if (li[1]==null)//如果为null直接加到树上
this.treeView1.Nodes.Add(n);
else
node.Nodes.Add(n);
CreateTree(n, GetList(listTree, li[0]));
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询