
Solution To "Old school tree display"
By: a guest on
Sep 10th, 2010 | syntax:
C# | size: 1.08 KB | hits: 31 | expires: Never
// My solution to the challenge posted here:
// http://blogs.msdn.com/b/ericlippert/archive/2010/09/09/old-school-tree-display.aspx
// by Allon Guralnek
public static void PrintTree(Node root)
{
PrintTreeInternal(root, null, false);
}
private static void PrintTreeInternal(Node node, string treeTrunk, bool isLastSibling)
{
if (treeTrunk != null)
Console.WriteLine(treeTrunk + (isLastSibling ? "└─" : "├─") + node.Text);
else
Console.WriteLine(node.Text); // When 'treeTrunk' is null, 'node' is the root.
for (int i = 0; i < node.Children.Count; i++)
{
Node child = node.Children[i];
string nextTreeTrunk;
bool isLastChild = i == node.Children.Count - 1;
if (treeTrunk == null)
{
nextTreeTrunk = "";
}
else
{
if (isLastSibling)
nextTreeTrunk = treeTrunk + " ";
else
nextTreeTrunk = treeTrunk + "│ ";
}
PrintTreeInternal(child, nextTreeTrunk, isLastChild);
}
}