Advertisement
Guest User

Solution To "Old school tree display"

a guest
Sep 10th, 2010
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement