I\'m trying to improve performance in our app. I\'ve got performance information in the form of a tree of calls, with the following node class:
public class
You'll need to keep track of an indentation string that's modified as you go deeper into the tree. To avoid adding extra |
characters, you'll also need to know whether the Node is the last child in that set.
public static void PrintTree(Node tree, String indent, Bool last)
{
Console.Write(indent + "+- " + tree.Name);
indent += last ? " " : "| ";
for (int i = 0; i < tree.Children.Count; i++)
{
PrintTree(tree.Children[i], indent, i == tree.Children.Count - 1);
}
}
When called like this:
PrintTree(node, "", true)
It will output text like this:
+- root
+- branch-A
| +- sibling-X
| | +- grandchild-A
| | +- grandchild-B
| +- sibling-Y
| | +- grandchild-C
| | +- grandchild-D
| +- sibling-Z
| +- grandchild-E
| +- grandchild-F
+- branch-B
+- sibling-J
+- sibling-K
If you happen to have a very deep tree and your call stack size is limited, you can instead do a static, non-recursive tree traversal to output the same result:
public static void PrintTree(Node tree)
{
List firstStack = new List();
firstStack.Add(tree);
List> childListStack = new List>();
childListStack.Add(firstStack);
while (childListStack.Count > 0)
{
List childStack = childListStack[childListStack.Count - 1];
if (childStack.Count == 0)
{
childListStack.RemoveAt(childListStack.Count - 1);
}
else
{
tree = childStack[0];
childStack.RemoveAt(0);
string indent = "";
for (int i = 0; i < childListStack.Count - 1; i++)
{
indent += (childListStack[i].Count > 0) ? "| " : " ";
}
Console.WriteLine(indent + "+- " + tree.Name);
if (tree.Children.Count > 0)
{
childListStack.Add(new List(tree.Children));
}
}
}
}