• 树的显示


    控制台显示

    public static string DrawTree<T>(this BinaryTreeBase<T> tree) where T : IComparable<T>
    {
        return string.Join("
    ", RecursivelyDrawTree(tree.Root, out _, out _));
    }
    private static List<string> RecursivelyDrawTree<T>(BTNode<T> node, out int positionOutput, out int widthOutput)
        where T : IComparable<T>
    {
        positionOutput = widthOutput = 0;
        if (node == null)
        {
            return new List<string>();
        }
        // 结点内容标签
        var label = node.Data.ToString();
        var leftLines = RecursivelyDrawTree(node.LeftChild, out int leftPos, out int leftWidth);
        var rightLines = RecursivelyDrawTree(node.RightChild, out int rightPos, out int rightWidth);
        // 计算填充
        int middle = Math.Max(Math.Max(2, label.Length), (rightPos + leftWidth - leftPos + 1));
        int pos_out = leftPos + middle / 2;
        int width_out = leftPos + middle + rightWidth - rightPos;
        while (leftLines.Count < rightLines.Count)
        {
            leftLines.Add(new string(' ', leftWidth));
        }
        while (rightLines.Count < leftLines.Count)
        {
            rightLines.Add(new string(' ', rightWidth));
        }
        if ((middle - label.Length % 2 == 1) && (label.Length < middle) && (node.Parent != null && node.IsLeftChild))
        {
            label += ".";
        }
        // 格式化结点标签
        label = label.PadCenter(middle, '.');
        var lbChars = label.ToCharArray();
        if (lbChars[0] == '.')
        {
            lbChars[0] = ' ';
        }
        if (lbChars[lbChars.Length - 1] == '.')
        {
            lbChars[lbChars.Length - 1] = ' ';
        }
        label = string.Join("", lbChars);
        // 构造列表
        string leftBranch = node.HasLeftChild ? "/" : " ";
        string rightBranch = node.HasRightChild ? "\" : " ";
        var rslt = new List<string>()
        {
            (new string(' ',leftPos))+label+(new string(' ',(rightWidth-rightPos))),
            (new string(' ',leftPos))+leftBranch+(new string(' ',(middle-2)))+rightBranch+(new string(' ',(rightWidth-rightPos))),
        };
        // 将右线和左线添加到最终列表中
        rslt.AddRange(leftLines.Zip(rightLines, (left, right) => left + (new string(' ', (width_out - leftWidth - rightWidth))) + right));
    
        widthOutput = width_out;
        positionOutput = pos_out;
        return rslt;
    }
    

    前台显示

  • 相关阅读:
    NOI-01:查找最接近的元素 基本二分
    C#学习笔记之——数据库操作的相关类
    Lua学习笔记——环境安装(Windows和MacOS)和在MacOS安装时错误解决方法
    Ubuntu下对数据库的操作
    Git常用操作
    [Unity游戏开发]常用类之Time类
    [Unity游戏开发]四元数Quaternion
    [Unity游戏开发]常用类之Transform类
    [Unity游戏开发]常用类之Component类
    [Unity游戏开发]射线(Ray)
  • 原文地址:https://www.cnblogs.com/wesson2019-blog/p/14721439.html
Copyright © 2020-2023  润新知