public
Last active

  • Download Gist
tree.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
sealed class Dumper
{
static public string Dump(Node root) {
return Dump(root, new List<bool>{});
}
 
// isLastPath - for every node in the current path, is it the last child?
static internal string Dump(Node n, List<bool> isLastPath) {
string bar = "¦";
string junction = "+";
string line = "-";
string turn = "+";
string result = "";
int depth = (isLastPath.Count);
 
// ascii-art nodes
if (depth > 0) {
bool nodeIsLastChild = isLastPath.Last();
// leave out leaf node
IEnumerable<bool> ancestorsAreLast = isLastPath.Take(isLastPath.Count-1);
// draw lines for parents
foreach(bool isLast in ancestorsAreLast) {
if (isLast) {
result += " ";
}
else {
result += bar + " ";
}
}
// draw lines for child
if (nodeIsLastChild) {
result += turn + line;
}
else {
result += junction + line;
}
}
// draw text node
result += n.Text + "\n";
int num = n.Children.Count;
int j = 0;
foreach(Node child in n.Children) {
List<bool> newPath = new List<bool>();
newPath.AddRange(isLastPath);
newPath.Add( j == num-1 );
result += Dump(child, newPath);
j++;
}
return result;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.