Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active June 28, 2022 08:08
Show Gist options
  • Save lejonmanen/0580091a3ff824fcce537fe5523e4ce8 to your computer and use it in GitHub Desktop.
Save lejonmanen/0580091a3ff824fcce537fe5523e4ce8 to your computer and use it in GitHub Desktop.
Pretty print the contents of a binary search tree
public void Print()
{
Queue<Node<T>?> nodes = new Queue<Node<T>?>();
Queue<Node<T>?> newNodes = new Queue<Node<T>?>();
nodes.Enqueue(Root);
int depth = 0;
bool exitCondition = false;
while (nodes.Count > 0 && !exitCondition)
{
depth++;
newNodes = new Queue<Node<T>?>();
string xs = "[";
foreach (var maybeNode in nodes)
{
string data = maybeNode == null ? " " : "" + maybeNode.Data;
if (maybeNode == null)
{
xs += "_, ";
newNodes.Enqueue(null);
newNodes.Enqueue(null);
}
else
{
Node<T> node = maybeNode;
string s = node.Data.ToString();
xs += s.Substring(0, Math.Min(4, s.Length)) + ", ";
if (node.LeftChild != null) newNodes.Enqueue(node.LeftChild);
else newNodes.Enqueue(null);
if (node.RightChild != null) newNodes.Enqueue(node.RightChild);
else newNodes.Enqueue(null);
}
}
xs = xs.Substring(0, xs.Length - 2) + "]";
Console.WriteLine(xs);
nodes = newNodes;
exitCondition = true;
foreach (var m in nodes)
{
if (m != null) exitCondition = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment