怎样打印树结构?牛人帮忙。。。

来源:百度知道 编辑:UC知道 时间:2024/06/04 23:37:36
如我想要打印这样的树:
program
|__compoundSentence
|__Sentence
| |__declareVariable
|__Sentence
...
program是根结点,compoundSentence是program的子结点,sentence是compoundSentence的子结点,declareVariable是Sentence的子结点。
这个程序要怎样写呢?
如:
program
|__compoundSentence
      |__Sentence
      |        |__declareVariable
      |__Sentence

你这种树需要一种存储结构,我采用的是双亲链表表示法,{节点名称,父节点名称},如果是根节点,父节点名称为null,只不过在这里是线性结构.我做了一个Winforms例子,list内的结构是String[]类型.先拖一个TreeView 控件

private List<string[]> listTree = new List<string[]>();

private void Form1_Load(object sender, EventArgs e)
{
listTree.Add(new string[] { "program", null });//树存储结构初始化
listTree.Add(new string[] { "compoundSentence", "program" });
listTree.Add(new string[] { "Sentence", "compoundSentence" });
listTree.Add(new string[] { "declareVariable", "Sentence" });
listTree.Add(new string[] { "Sentence ", "compoundSentence" });

CreateTree(null, GetList(listTree, null));//创建树
}

private List<string[]> GetList(List<string[]> list, string s)//此方法寻找子节点集合
{
List