当前位置:   article > 正文

非二叉树 后序遍历非递归_非二叉树的遍历

非二叉树的遍历
  1. public partial class Tree
  2. {
  3. public string value;
  4. public IList<Tree> children;
  5. int flag = 0; //节点遍历次数
  6. }
  7. Tree tree = new Tree() { value = "Root" };
  8. tree.children = new List<Tree>();
  9. tree.children.Add(new Tree() { value = "X" });
  10. tree.children.Add(new Tree() { value = "Y" });
  11. tree.children.Add(new Tree() { value = "Z" });
  12. tree.children[0].children = new List<Tree>();
  13. tree.children[0].children.Add(new Tree() { value = "XX" });
  14. tree.children[0].children.Add(new Tree() { value = "XY" });
  15. tree.children[0].children.Add(new Tree() { value = "XZ" });
  16. tree.children[1].children = new List<Tree>();
  17. tree.children[1].children.Add(new Tree() { value = "YX" });
  18. tree.children[1].children.Add(new Tree() { value = "YY" });
  19. tree.children[1].children.Add(new Tree() { value = "YZ" });
  20. tree.children[2].children = new List<Tree>();
  21. tree.children[2].children.Add(new Tree() { value = "ZX" });
  22. tree.children[2].children.Add(new Tree() { value = "ZY" });
  23. tree.children[2].children.Add(new Tree() { value = "ZZ" });
  24. if (tree != null)
  25. {
  26. //后序遍历
  27. Stack<Tree> stack = new Stack<Tree>();
  28. Tree node = tree;
  29. stack.Push(node); //root
  30. while(stack.Any())
  31. {
  32. node = stack.Peek();
  33. node.flag++;
  34. if( node.children == null || node.flag > 1)
  35. {
  36. Console.WriteLine(node.value);
  37. stack.Pop();
  38. }
  39. else
  40. {
  41. for (int i = node.children.Count - 1; i >= 0; i--)
  42. {
  43. stack.Push(node.children[i]);
  44. }
  45. }
  46. }
  47. }

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号