Reputation: 3934
I'm implementing a C# program that have some binary trees.
Is there some addin to visual studio which I can use for debugging?
I need it to draw the tree in run time.
Upvotes: 2
Views: 3313
Reputation: 173
I found very useful to get a DOT representation of the binary tree from the magnifying glass when debugging and paste it on any Graphviz online site such as dreampuf.github.io/GraphvizOnline.
[DebuggerDisplay("{DebuggerDisplay}")]
public class BinaryTree
{
private string DebuggerDisplay => GetDotRepresentation();
public string GetDotRepresentation() {
var sb = new StringBuilder();
sb.AppendLine("digraph BST {");
GetDotRepresentation(this.Root, sb);
sb.AppendLine("}");
return sb.ToString();
}
private void GetDotRepresentation(Node root, StringBuilder sb)
{
if (root == null) return;
if (root.Left != null) {
sb.AppendLine($"{root.Value} -> {root.Left.Value}");
}
if (root.Right != null)
{
sb.AppendLine($"{root.Value} -> {root.Right.Value}");
}
GetDotRepresentation(root.Left, sb);
GetDotRepresentation(root.Right, sb);
}
}
Upvotes: 1
Reputation: 203804
Here's a simple binary tree with a method to convert it to a string representation. You probably have your own binary tree class, but you can use this same general algorithm with that.
Here I use a single tab to separate each node. If the ToString
of the content of each node is larger than 8 (?) characters you may need to instead use some larger number of spaces, multiple tabs, or add some character to the start of the string of each node to help you visualize it.
public class Node<T>
{
public T Data { get; set; }
public Node<T> Left { get; set; }
public Node<T> Right { get; set; }
public string displayNode()
{
StringBuilder output = new StringBuilder();
displayNode(output, 0);
return output.ToString();
}
private void displayNode(StringBuilder output, int depth)
{
if (Right != null)
Right.displayNode(output, depth+1);
output.Append('\t', depth);
output.AppendLine(Data.ToString());
if (Left != null)
Left.displayNode(output, depth+1);
}
}
Then to actually use it:
Node<string> root = new Node<string>() { Data = "root" };
root.Left = new Node<string>() { Data = "1" };
root.Right = new Node<string>() { Data = "2" };
root.Left.Left = new Node<string>() { Data = "3" };
root.Left.Right = new Node<string>() { Data = "4" };
Console.WriteLine(root.displayNode());
Upvotes: 2
Reputation: 625
Not the best way, and probably not very good if the tree is big, but you can create a recursive function like :
public String ToString()
{
return id + "{" + a.ToString() + ";" + b.ToString() + "}";
}
With : id
the id of the current node, a
and b
the two child
EDIT
You need to be absolutely sure that this is a tree and that it does not contains any cycle.
Upvotes: 2