| 利斌's profileThe time when I was youn...PhotosBlogLists | Help |
|
June 12 树 - 孩子表示的多叉树
public struct TreeHead { public int childCount; //子树的数目 public string data; public TreeNode FirstChild; //指向第一个子树 }
public class TreeNode { public string data; public TreeNode Next;
//构造函数用了XmlNode的特性,对与其他类型的数据可以使用相应的方式来构造 //这个构造函数用递归将node的所有相邻节点都链了起来 //链接方向是从左至右 public TreeNode(XmlNode node) { data = node.Name; if (node.NextSibling != null) Next = new TreeNode(node.NextSibling); else Next = null; } }
public class Tree { List<TreeHead> heads = new List<TreeHead>();//这里用了.NET的类库List来存储头节点,因为.NET中动态扩展数组的长度比较困难,不太常见,所以使用了List这个类库
public Tree(string xmlPath) { XmlDocument xdoc = new XmlDocument(); xdoc.Load(xmlPath); Initialize(xdoc.FirstChild); }
public void Initialize(XmlNode root) { TreeHead th = new TreeHead(); th.childCount = root.ChildNodes.Count; th.data = root.Name; //heads.Add(th); 我本来以为这行放在这里和放在后面是一样的,但结果不一样,放在这里th.FirstChild竟然一直是null,奇怪
XmlNode node = root.FirstChild;
if (node != null) { TreeNode tn = new TreeNode(node); th.FirstChild = tn; //这里将子节点创建出来,并挂在头节点上 }
heads.Add(th); //这里将头节点加入列表,见上面注释掉的那行
//循环构造子节点 for (int i = 0; i < root.ChildNodes.Count; i++) { Initialize(root.ChildNodes[i]); //递归构造子节点 }
}
//遍历输出 public void Output() { foreach (TreeHead th in heads) { Console.WriteLine();
TreeNode tn = th.FirstChild; Console.Write(th.data);
Console.Write("-");
while (tn != null) { Console.Write(tn.data + " "); tn = tn.Next; } } } } |
|
|