2

いくつかのバイナリツリーを持つC#プログラムを実装しています。

デバッグに使用できるVisualStudioのアドインはありますか?

実行時にツリーを描画するために必要です。

4

3 に答える 3

2

最善の方法ではなく、ツリーが大きい場合はおそらくあまり良くありませんが、次のような再帰関数を作成できます。

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

With:id現在のノードのIDab2つの子

編集

これがツリーであり、サイクルが含まれていないことを絶対に確認する必要があります。

于 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表現を取得し、dreampuf.github.io/ GraphvizOnlineなどのGraphvizオンラインサイトに貼り付けると非常に便利であることがわかりました。

[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 に答える