2

我正在实现一个有一些二叉树的 C# 程序。

是否有一些可用于调试的 Visual Studio 插件?

我需要它在运行时绘制树。

4

3 回答 3

2

不是最好的方法,如果树很大,可能也不是很好,但是您可以创建一个递归函数,例如:

public String ToString()
{
    return id + "{" + a.ToString() + ";" + b.ToString() + "}";
}

with :id当前节点的id,a以及b两个孩子

编辑

您需要绝对确定这是一棵树并且它不包含任何循环。

于 2012-07-25T15:34:33.357 回答
2

这是一个简单的二叉树,带有将其转换为字符串表示的方法。您可能有自己的二叉树类,但您可以使用相同的通用算​​法。

在这里,我使用单个选项卡来分隔每个节点。如果ToString每个节点的内容大于 8 (?) 个字符,您可能需要使用更多的空格、多个制表符,或者在每个节点的字符串开头添加一些字符以帮助您将其可视化。

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);

    }
}

然后实际使用它:

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());
于 2012-07-25T16:01:21.283 回答
0

我发现在调试时从放大镜中获取二叉树的 DOT 表示并将其粘贴到任何 Graphviz 在线站点(例如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);
    }
 }  
于 2021-09-19T23:16:22.547 回答