Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

# Solution To "Old school tree display"

By: a guest on Sep 10th, 2010  |  syntax: C#  |  size: 1.08 KB  |  views: 33  |  expires: Never
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
Top