树的数据结构是从根节点开枝散叶,父节点唯一。
首先初始化要展示的数据,用Dictionary保存:
Dictionary<int, List<int>> dt;
初始化数据,数字0为根节点,字典中的key有[0,1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44]:
private void InitData() { dt = new Dictionary<int, List<int>>(); dt[0] = new List<int>(); for (int i = 1; i < 5; i++) { dt[0].Add(i); dt[i] = new List<int>(); for (int j = 1; j < 5; j++) { dt[i].Add(i * 10 + j); dt[i * 10 + j] = new List<int>(); for (int k = 1; k < 5; k++) dt[i * 10 + j].Add(i * 100 + j * 10 + k); } } }
填充节点的递归函数,将节点作为参数传递,程序从数据中找到节点的子数据,再创建为节点填充,然后递归调用:
private void FillNode(TreeNode node) { int id = Convert.ToInt16(node.Text); if (!dt.ContainsKey(id)) return; foreach (int val in dt[id]) { TreeNode subNode = new TreeNode(); subNode.Text = val.ToString(); node.Nodes.Add(subNode); FillNode(subNode); } }
填充树的根节点0,然后将根节点作为参数调用递归函数:
private void FillTreeView() { TreeNode rootNode = new TreeNode(); rootNode.Text = "0"; this.treeView1.Nodes.Add(rootNode); FillNode(rootNode); this.treeView1.ExpandAll(); }
运行程序:
标签:Node,TreeNode,递归,int,Add,new,dt,TreeView,节点 From: https://www.cnblogs.com/cfsl/p/17580751.html