.NET 2.x Удаление из бинарного дерева. - C#
Формулировка задачи:
Собственно есть дерево.
Как из него написать удаление элемента?
В данном случае по параметру
p.Ves
сам классclass treeS
{
struct People
{
private Int32 _Ves;
private string _Name;
public Int32 value
{
get { return _Ves; }
set { _Ves = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
private Int32 count;
private treeS left;
private treeS right;
People p = new People();
public Int32 Ves
{
get { return p.value; }
}
public String Name
{
get { return p.Name; }
}
// вставка
public void Add(Int32 value, String Name)
{
if (p.value == 0)
{
p.value = value;
p.Name = Name;
}
else
{
if (p.value > value)
{
if (left == null)
this.left = new treeS();
left.Add(value, Name);
}
else if (p.value < value)
{
if (right == null)
this.right = new treeS();
right.Add(value, Name);
}
else
throw new Exception("Узел уже существует");
}
this.count = Recount(this);
}
// поиск числа
public treeS Search(Int32 value)
{
if (p.value == value)
{
return this;
}
else if (p.value > value)
{
if (left != null)
return this.left.Search(value);
else
throw new Exception("Искомого узла в дереве нет");
}
else
{
if (right != null)
return this.right.Search(value);
else
throw new Exception("Искомого узла в дереве нет");
}
}
// поиск строки
public treeS Search(String value)
{
if (p.Name == value)
{
return this;
}
else if (p.Name.CompareTo(value)==1)
{
if (left != null)
return this.left.Search(value);
else
throw new Exception("Искомого узла в дереве нет");
}
else
{
if (right != null)
return this.right.Search(value);
else
throw new Exception("Искомого узла в дереве нет");
}
}
// отображение в строку
public override string ToString()
{
return this.ToString(this);
}
// отображение в строку
private string ToString(treeS t)
{
string result = "";
if (t.left != null)
result += ToString(t.left);
result += t.p.value + " " + t.p.Name + ";\r\n";
if (t.right != null)
result += ToString(t.right);
return result;
}
// подсчет
private int Recount(treeS t)
{
int count = 0;
if (t.left != null)
count += Recount(t.left);
count++;
if (t.right != null)
count += Recount(t.right);
return count;
}
// очистка
public void Clear()
{
count = 0;
p.value = 0;
this.left = null;
this.right = null;
}
// проверка пустоты
public bool IsEmpty()
{
if (p.value == 0)
return true;
else
return false;
}
}Решение задачи: «.NET 2.x Удаление из бинарного дерева.»
textual
Листинг программы
public void Del(String value)
{
if (this.Name != null)
{
if (value == this.Name)
{
if (this.right == null && this.left == null)
{
this.Clear();
}
else
{
if (this.right == null)
{
this.p.value = this.left.Ves;
this.p.Name = this.left.Name;
this.left = this.left.left;
}
else
{
if (this.left == null)
{
this.p.value = this.right.Ves;
this.p.Name = this.right.Name;
this.right = this.right.right;
}
else
{
///????????????????
}
}
}
}
else
{
if (value.CompareTo(this.Name) == 1)
{
this.right.Del(value);
}
else
{
this.left.Del(value);
}
}
}
this.count = Recount(this);
}