Created
          February 20, 2015 01:26 
        
      - 
      
- 
        Save i3arnon/b814eae0c648d9e15578 to your computer and use it in GitHub Desktop. 
    Zigzag
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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