Created
September 2, 2012 20:13
-
-
Save Toshakins/3604140 to your computer and use it in GitHub Desktop.
BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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