赞
踩
- public partial class Tree
- {
- public string value;
- public IList<Tree> children;
- int flag = 0; //节点遍历次数
- }
-
- Tree tree = new Tree() { value = "Root" };
- tree.children = new List<Tree>();
-
- tree.children.Add(new Tree() { value = "X" });
- tree.children.Add(new Tree() { value = "Y" });
- tree.children.Add(new Tree() { value = "Z" });
-
- tree.children[0].children = new List<Tree>();
- tree.children[0].children.Add(new Tree() { value = "XX" });
- tree.children[0].children.Add(new Tree() { value = "XY" });
- tree.children[0].children.Add(new Tree() { value = "XZ" });
-
- tree.children[1].children = new List<Tree>();
- tree.children[1].children.Add(new Tree() { value = "YX" });
- tree.children[1].children.Add(new Tree() { value = "YY" });
- tree.children[1].children.Add(new Tree() { value = "YZ" });
-
- tree.children[2].children = new List<Tree>();
- tree.children[2].children.Add(new Tree() { value = "ZX" });
- tree.children[2].children.Add(new Tree() { value = "ZY" });
- tree.children[2].children.Add(new Tree() { value = "ZZ" });
-
-
- if (tree != null)
- {
- //后序遍历
- Stack<Tree> stack = new Stack<Tree>();
-
- Tree node = tree;
-
- stack.Push(node); //root
-
- while(stack.Any())
- {
- node = stack.Peek();
- node.flag++;
-
- if( node.children == null || node.flag > 1)
- {
- Console.WriteLine(node.value);
-
- stack.Pop();
- }
- else
- {
- for (int i = node.children.Count - 1; i >= 0; i--)
- {
- stack.Push(node.children[i]);
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。