C# Display a Binary Search Tree in Console

前端 未结 3 1454
我寻月下人不归
我寻月下人不归 2021-01-31 04:27

I have simple binary search tree

public class BNode
{
    public int item;
    public BNode right;
    public BNode left;

    public BNode(int item)
    {
             


        
3条回答
  •  迷失自我
    2021-01-31 04:56

    If your tree is in the form of a QuickGraph IBidirectionalGraph, you could print it recursively like this:

    static void PrintVertex(IBidirectionalGraph> graph, TVertex vertex, Func labelSelector, bool[] isLastVertexIntendations = null)
    {
        var prefix = string.Concat(Enumerable.Concat(
            /*up to last*/isLastVertexIntendations.NeverNull().Reverse().Skip(1).Reverse().Select(isLast => isLast ? "  " : "│ "),
            /*last*/isLastVertexIntendations.NeverNull().Reverse().Take(1).Select(isLast => isLast ? "└─" : "├─")
        ));
        Console.Write(prefix);
        Console.WriteLine(labelSelector(vertex));
        var edges = graph.OutEdges(vertex);
        foreach (var edge in edges)
        {
            PrintVertex(graph, edge.Target, labelSelector, isLastVertexIntendations: isLastVertexIntendations.NeverNull().Concat(new[] { edge == edges.Last() }).ToArray());
        }
    }
    

提交回复
热议问题