控制台显示
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;
}
前台显示