Skip to content

Instantly share code, notes, and snippets.

@HoraceBury
Created November 3, 2024 06:39
Show Gist options
  • Save HoraceBury/8323c64372e5ab9ebd21f6f72e30e324 to your computer and use it in GitHub Desktop.
Save HoraceBury/8323c64372e5ab9ebd21f6f72e30e324 to your computer and use it in GitHub Desktop.
Binary Sort Tree with example use
using System.Collections;
// var root = new Node<int>(10);
var root = new Node<int>(10, NumberComparer);
root.Insert(9);
root.Insert(5);
root.Insert(15);
root.Insert(3);
root.Insert(9);
root.Insert(7);
root.Insert(12);
root.Insert(18);
// root.Traverse();
// foreach (var value in root)
// Console.WriteLine(value);
Console.WriteLine($"Length: {root.Length}");
Console.WriteLine(root.ToString());
static int NumberComparer(int a, int b) => a.CompareTo(b) * -1;
public class Node<T>(T value, Func<T, T, int>? comparer = null) : IEnumerable<T> where T : IComparable<T>
{
public T Value = value;
public Node<T>? Left;
public Node<T>? Right;
public int Length { get; private set; } = 1;
private readonly Func<T, T, int>? Comparer = comparer;
public IEnumerator<T> GetEnumerator()
{
if (Left != null)
foreach (var value in Left)
yield return value;
yield return Value;
if (Right != null)
foreach (var value in Right)
yield return value;
}
public void Insert(T newValue)
{
Length++;
var compared = Comparer == null ? newValue.CompareTo(Value) : Comparer(newValue, Value);
if (compared < 0)
{
if (Left == null)
Left = new Node<T>(newValue, Comparer);
else
Left.Insert(newValue);
}
else
{
if (Right == null)
Right = new Node<T>(newValue, Comparer);
else
Right.Insert(newValue);
}
}
public string ToString(string separator = ",") => String.Join(separator, this.ToArray<T>());
IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment