Skip to content

Instantly share code, notes, and snippets.

@Toshakins
Created September 2, 2012 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Toshakins/3604140 to your computer and use it in GitHub Desktop.
Save Toshakins/3604140 to your computer and use it in GitHub Desktop.
BST
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace gurren_laggan
{
class Program
{
public delegate void ChangedEventHandler(object sender, EventArgs e);
interface Tree<T> where T : IComparable //does this take any effect?
{
void insert(T x);
void remove(T x);
Tree<T> search(T x);
}
class BST<T> : Tree<T> where T : IComparable
{
BST<T> left, right;
T data;
public BST(T x)
{
data = x;
left = right = null;
}
public event ChangedEventHandler Changed;
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
public void insert(T x)
{
BST<T> tmp = this;
do
{
if (x.CompareTo(tmp.data) < 0)
if (tmp.left != null) tmp = tmp.left;
else
{
tmp.left = new BST<T>(x);
OnChanged(EventArgs.Empty); return;
}
else if (tmp.right != null) tmp = tmp.right;
else
{
tmp.right = new BST<T>(x);
OnChanged(EventArgs.Empty); return;
}
} while (true);
}
public void remove(T x)
{
BST<T> tmp = (BST<T>)search(x);
if (tmp == null) return;
if (tmp.right == null) { tmp = tmp.left; return; }
BST<T> candidate = tmp.right;
while (candidate.left != null)
candidate = candidate.left;
tmp.data = candidate.data;
if (candidate.right != null)
{
candidate.data = candidate.right.data;
candidate.left = candidate.right.left;
candidate.right = candidate.right.right;
}
else candidate = null;
OnChanged(EventArgs.Empty);
}
public Tree<T> search(T x)
{
BST<T> tmp = this;
while (tmp != null)
{
if (tmp.data.CompareTo(x) == 0)
return tmp;
else if (x.CompareTo(tmp.data) < 0) tmp = tmp.left;
else tmp = tmp.right;
}
return null;
}
}
static void printf(object o, EventArgs e)
{
Console.WriteLine("Alonso, allons-y!");
}
static void Main(string[] args)
{
string[] s = System.IO.File.ReadAllText(@"E:\src\gurren-laggan\gurren-laggan\input.txt").Split(' ');
int[] a = new int[s.Length];
BST<int> t = new BST<int>(int.Parse(s[0]));
t.Changed += new ChangedEventHandler(printf);
for (int i = 1; i < s.Length; ++i)
t.insert(int.Parse(s[i]));
t.remove(3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment