View difference between Paste ID: BXxV8Nez and
SHOW:
|
|
- or go back to the newest paste.
1 | - | |
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 | } |