var tree = new Node("大纲", new List<Node> { new Node("前言", new List<Node> { new Node("第一段", null), new Node("第二段", null) }), new Node("自然地理", new List<Node>{ new Node("第三段", null), new Node("第四段", null) }), new Node("工程地质条件", null) } );
public static IList<string> PreorderTraversal(Node root) { //返回的list var forReturn = new List<string>(); if (root == null) return forReturn; //定义一个栈 var stackTemp = new Stack<Node>(); //在栈的顶部插入根节点 stackTemp.Push(root); while (stackTemp.Any()) { //移除栈顶部的对象 var curNode = stackTemp.Pop(); //将该对象add至返回的list中 forReturn.Add(curNode.val); if (curNode.children != null) { for (var i = curNode.children.Count - 1; i >= 0; i--) stackTemp.Push(curNode.children[i]); } } return forReturn; }