如何在 C# 中直观地打印 n 叉树?

How to visually print a n-ary tree in c#?

我用c#做了一个基本的n叉树:

树:

public class Tree<T>
{
    private Node<T> root;

    public Tree()
    {
        root = null;
    }


    public Node<T> Root
    {
        get
        {
            return root;
        }

        set
        {
            root = value;
        }
    }

    public T search (T data)
    {
        return (root != null) ? raiz.search(data) : default(T);
    }

}

节点:

public class Node<T>
{
    private T data;
    private List<Node<T>> childs;

    public Node(T data)
    {
        this.data = data;
        this.childs = null;
    }

    public T Data
    {
        get
        {
            return data;
        }

        set
        {
            data = value;
        }
    }

    public List<NodoArbol<T>> Childs
    {
        get
        {
            return childs;
        }

        set
        {
            childs = value;
        }
    }

    public void addChild(Node node)
    {
        if (child == null)
        {
            childs = new List<Node<T>>();
        }
            childs.Add(node);

    }


    public T search(T data)
    {
        if (this.data.Equals(data))
        {
            return this.data;
        }else
        {
            for (int i = 0; i < childs.Count; i++)
            {
                T aux = childs.ElementAt(i).search(data);
                if (aux != null)
                {
                    return aux;
                }
            }
            return default(T);
        }
    }
}

我想要树的可视化表示,以便我可以快速测试以查看子节点和节点是否在正确的位置并测试我的遍历(预 order/in order/post 顺序) 像这样

如果足以让您将其输出到控制台:

public void PrintTree(Node node, int indentSize, int currentLevel)
{
    var currentNode = string.Format("{0}{1}", new string(" ",indentSize*currentLevel, node.Data);
    Console.WriteLine(currentNode)
    foreach(var child in node.Children)
    {
        PrintTree(child, indentSize, currentLevel+1);
    }
}

然后这样称呼它

PrintTree(yourTreeInstance.Root,4,0);

您也可以使用Debug.WriteLine输出到调试控制台而不是主控制台