Skip to content

Instantly share code, notes, and snippets.

@i3arnon
Created February 20, 2015 01:26
Show Gist options
  • Save i3arnon/b814eae0c648d9e15578 to your computer and use it in GitHub Desktop.
Save i3arnon/b814eae0c648d9e15578 to your computer and use it in GitHub Desktop.
Zigzag
internal class Program
{
private static void Main()
{
var head = new Node();
CreateTree(head, 4, 2);
head.Print(string.Empty, true);
Console.WriteLine("Zigzag:");
var zig = new Stack<Node>();
var zag = new Stack<Node>();
var reverse = false;
zig.Push(head);
while (zig.Count > 0)
{
while (zig.Count > 0)
{
var node = zig.Pop();
foreach (var child in reverse ? node.Children.Reverse() : node.Children)
{
zag.Push(child);
}
Console.Write(node.Value + " ");
}
Console.WriteLine();
reverse = !reverse;
var temp = zig;
zig = zag;
zag = temp;
}
}
static void CreateTree(Node parent, int level, int count)
{
if (level == 0) return;
parent.Children = Enumerable.Repeat(-1, count).Select(_ => new Node()).ToArray();
foreach (var child in parent.Children)
{
CreateTree(child, level - 1, count);
}
}
class Node
{
private static int _index = 1;
public int Value { get; private set; }
public Node[] Children { get; set; }
public Node()
{
Value = _index;
_index++;
Children = new Node[0];
}
public void Print(string indent, bool last)
{
Console.Write(indent);
if (last)
{
Console.Write("\\-");
indent += " ";
}
else
{
Console.Write("|-");
indent += "| ";
}
Console.WriteLine(Value);
for (var i = 0; i < Children.Length; i++)
Children[i].Print(indent, i == Children.Length - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment