-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRbTreeExtension.cs
More file actions
68 lines (63 loc) · 2.12 KB
/
Copy pathRbTreeExtension.cs
File metadata and controls
68 lines (63 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Text;
namespace RbTree;
public static class RbTreeExtension
{
public static void ShowLog(this RbTree tree)
{
StringBuilder sb = new("层序遍历:\n");
DoShowLog(tree.Root, sb);
Console.WriteLine(sb);
}
private static void DoShowLog(Node root, StringBuilder sb)
{
Queue<Node?> queue = new();
queue.Enqueue(root);
int curLayer = 0;
int totalLayer = GetHeight(root);
while (queue.Count > 0)
{
int count = queue.Count;
string layerOutput = "";
++curLayer;
bool isFirstSiblingInCurrentLayer = true;
for (int i = 0; i < count; ++i)
{
var indent = (int)(Math.Pow(2, (totalLayer - curLayer)));
if (curLayer > 1 && !isFirstSiblingInCurrentLayer)
indent <<= 1;
var curNode = queue.Dequeue();
if (curNode != Node.Nil && curNode != null)
{
var mark = (curNode.Color == Color.Red) ? 'R' : 'B';
layerOutput += Indent(indent - 1) + mark + curNode.Key.ToString().PadLeft(3, ' ');
queue.Enqueue(curNode.Left);
queue.Enqueue(curNode.Right);
}
else if (curLayer <= totalLayer)
{
layerOutput += Indent(indent - 1) + "NULL";
if (curLayer < totalLayer)
{
queue.Enqueue(null);
queue.Enqueue(null);
}
}
isFirstSiblingInCurrentLayer = false;
}
sb.AppendLine(layerOutput);
sb.AppendLine();
}
}
private static string Indent(int n)
{
return string.Concat(Enumerable.Repeat(" ", n));
}
private static int GetHeight(Node node)
{
if (node == Node.Nil)
return 0;
var leftHeight = GetHeight(node.Left);
var rightHeight = GetHeight(node.Right);
return Math.Max(leftHeight, rightHeight) + 1;
}
}