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();
}
}