This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Solution To "Old school tree display"

By: a guest on Sep 10th, 2010  |  syntax: C#  |  size: 1.08 KB  |  views: 31  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // My solution to the challenge posted here:
  2. // http://blogs.msdn.com/b/ericlippert/archive/2010/09/09/old-school-tree-display.aspx
  3. // by Allon Guralnek
  4.  
  5. public static void PrintTree(Node root)
  6. {
  7.     PrintTreeInternal(root, null, false);
  8. }
  9. private static void PrintTreeInternal(Node node, string treeTrunk, bool isLastSibling)
  10. {
  11.     if (treeTrunk != null)
  12.         Console.WriteLine(treeTrunk + (isLastSibling ? "└─" : "├─") + node.Text);
  13.     else
  14.         Console.WriteLine(node.Text);    // When 'treeTrunk' is null, 'node' is the root.
  15.  
  16.  
  17.     for (int i = 0; i < node.Children.Count; i++)
  18.     {
  19.         Node child = node.Children[i];
  20.         string nextTreeTrunk;
  21.         bool isLastChild = i == node.Children.Count - 1;
  22.  
  23.         if (treeTrunk == null)
  24.         {
  25.             nextTreeTrunk = "";
  26.         }
  27.         else
  28.         {
  29.             if (isLastSibling)
  30.                 nextTreeTrunk = treeTrunk + "  ";
  31.             else
  32.                 nextTreeTrunk = treeTrunk + "│ ";
  33.         }
  34.  
  35.         PrintTreeInternal(child, nextTreeTrunk, isLastChild);
  36.     }
  37. }
clone this paste RAW Paste Data