using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static readonly Random r = new Random(12345); class Node { public int Value; public Node Left; public Node Right; public static Node Generate(int i) { if (i > 8) { return null; } var n = new Node(); n.Value = r.Next(0, 99); if (r.NextDouble() < 0.9) { n.Left = Generate(i + 1); } if (r.NextDouble() < 0.9) { n.Right = Generate(i + 1); } return n; } } enum SearchDirection { Left, Right, Done } static void Main(string[] args) { var root = Node.Generate(0); var nodes = new List<Node>(); var dirs = new List<SearchDirection>(); nodes.Add(root); dirs.Add(SearchDirection.Left); Console.Write("{0:D2}", root.Value); for (; nodes.Count > 0; ) { var n = nodes.Last(); var d = dirs.Last(); if (d == SearchDirection.Left && n.Left != null) { Console.Write("--{0:D2}", n.Left.Value); dirs[dirs.Count - 1] = SearchDirection.Right; nodes.Add(n.Left); dirs.Add(0); continue; } else if (d == SearchDirection.Right && n.Right != null) { Console.WriteLine(); for (var j = 0; j < nodes.Count; j++) { if (j == nodes.Count - 1) { Console.Write("└--"); } else if (dirs[j] != SearchDirection.Done && nodes[j].Right != null) { Console.Write("│ "); } else { Console.Write(" "); } } Console.Write("{0:D2}", n.Right.Value); dirs[dirs.Count - 1] = SearchDirection.Done; nodes.Add(n.Right); dirs.Add(0); } else { nodes.RemoveAt(nodes.Count - 1); dirs.RemoveAt(dirs.Count - 1); } } Console.ReadKey(); } }
Standard input is empty
36--37--35--63--54--96--81--17
│ │ │ │ │ └--37
│ │ │ │ └--35--02--75
│ │ │ │ │ └--46
│ │ │ │ └--62--93
│ │ │ └--08--58--44--52
│ │ │ │ └--88
│ │ │ └--79--46
│ │ │ └--33
│ │ └--20--34--23
│ │ │ └--68--55--41
│ │ │ │ └--02
│ │ │ └--36--42
│ │ │ └--37
│ │ └--61--62
│ │ └--63--02--04
│ │ │ └--14
│ │ └--10--45
│ │ └--68
│ └--25
└--30--44--54--87--12--04--43--03
│ │ │ │ │ │ └--25
│ │ │ │ │ └--28--81
│ │ │ │ │ └--73
│ │ │ │ └--61--30
│ │ │ └--89--11--65--80
│ │ │ │ │ └--18
│ │ │ │ └--86--30
│ │ │ │ └--41
│ │ │ └--17--84
│ │ │ └--28--86
│ │ │ └--63
│ │ └--05--97--44--06--00
│ │ │ │ │ └--45
│ │ │ │ └--04--19
│ │ │ │ └--02
│ │ │ └--74--56--07
│ │ │ │ └--42
│ │ │ └--89--40
│ │ │ └--61
│ │ └--03--76--31--12
│ │ │ │ └--31
│ │ │ └--70--51
│ │ │ └--20
│ │ └--35--05--85
│ │ │ └--01
│ │ └--26--97
│ │ └--85
│ └--76
└--36--57--42--66--59--14--05
│ │ │ │ └--86
│ │ │ └--59--70
│ │ │ └--37
│ │ └--69--57--50
│ │ │ └--84
│ │ └--80--63
│ │ └--30
│ └--74--44--84--98
│ │ │ └--44
│ │ └--40--66
│ └--90--85--90
│ │ └--47
│ └--37--89
└--84