Вставка нового узла в бинарное дерево - C#
Формулировка задачи:
Подскажите можно ли как-то реализовать, чтобы в консоле можно было вставлять новый узел, нахождение отца и правого, левого сыновей произвольной?
пробовал таким способом, но выдает кучу ошибок.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication36;
namespace ConsoleApplication36
{
//класс элемента связного списка
public sealed class ListElement<T1>
{
//суть - узел
private ListElement<T1> PrevElement;
private ListElement<T1> NextElement;
private T1 DateElement;
//новый элемент
public ListElement(ListElement<T1> PrevElement, ListElement<T1> NextElement, T1 DateElement)
{
this.PrevElement = PrevElement;
this.NextElement = NextElement;
this.DateElement = DateElement;
}
//замена частей узла
public ListElement<T1> GetSetNextElement
{
get { return this.NextElement; }
set { this.NextElement = value; }
}
public ListElement<T1> GetSetPrevElement
{
get { return this.PrevElement; }
set { this.PrevElement = value; }
}
public T1 GetSetDateElement
{
get { return this.DateElement; }
set { this.DateElement = value; }
}
}
class MyLinkedList<T1>
{
private ListElement<T1> LastElement;
private ListElement<T1> FirstElement;
private int count = 0;
//число элементов списка
public int NumberOfElements()
{
return count;
}
//добавить элемент в список
public void AddElement(T1 elem)
{
if (FirstElement == null)
{
ListElement<T1> NewElement = new ListElement<T1>(null, null, elem);
FirstElement = NewElement;
LastElement = NewElement;
}
else
{
ListElement<T1> NewElement = new ListElement<T1>(LastElement, null, elem);
LastElement.GetSetNextElement = NewElement;
LastElement = NewElement;
}
count++;
}
//Добавить элемент по индексу
public T1 AddToPosition(T1 elem, int index)
{
ListElement<T1> Last = LastElement;
ListElement<T1> Next = SearchElement(index);
if (index == 0)
{
FirstElement = new ListElement<T1>(null, null, elem);
FirstElement.GetSetNextElement = Next;
Next.GetSetPrevElement = FirstElement;
return default(T1);
}
ListElement<T1> Prev = SearchElement(index - 1);
ListElement<T1> NewElement = new ListElement<T1>(null, null, elem);
Prev.GetSetNextElement = NewElement;
NewElement.GetSetPrevElement = Prev;
Next.GetSetPrevElement = NewElement;
NewElement.GetSetNextElement = Next;
count++;
LastElement = Last;
return default(T1);
}
//удалить элемент по индексу
public T1 DeleteElement(int index)
{
ListElement<T1> Prev;
ListElement<T1> Next;
if (index == 0)
{
FirstElement = SearchElement(index + 1);
return default(T1);
}
Prev = SearchElement(index - 1);
Next = SearchElement(index + 1);
Prev.GetSetNextElement = Next;
Next.GetSetPrevElement = Prev;
count--;
return default(T1);
}
//прочитать элемент по индексу
public T1 ReadElement(int index)
{
ListElement<T1> Element = SearchElement(index);
return Element.GetSetDateElement;
}
//записать элемент по индексу
public T1 WriteElement(T1 elem, int index)
{
ListElement<T1> Element = SearchElement(index);
return Element.GetSetDateElement = elem;
}
//выбор направления поиска и поиск элемента
public ListElement<T1> SearchElement(int index)
{
//присваиваю первый или последний член списка
ListElement<T1> Prev = LastElement;
ListElement<T1> Next = FirstElement;
//Проверка на недопустимый индекс / проход с начала / конца списка.
if (index > count || index < 0)
{
throw new IndexOutOfRangeException();
}
else if (index < ((count + 1) / 2))
{
if (index == 0)
{
return FirstElement;
}
for (; index != 0; index--)
{
Next = Next.GetSetNextElement;
}
return Next;
}
else
{
for (; index < count; index++)
{
Prev = Prev.GetSetPrevElement;
}
return Prev;
}
}
//очистить список
public void DeleteAllElements()
{
FirstElement = null;
count = 0;
}
}
}
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int v = random.Next() % 100;
Console.Write(v + " ");
list.PushBack(v);
}
Console.WriteLine();
list.PushFront(1);
list.PushFront(2);
for (int i = 0; i < list.Count; i++)
Console.Write(list[i] + " ");
Console.WriteLine();
list.Erase(3);
for (int i = 0; i < list.Count; i++)
Console.Write(list[i] + " ");
Console.WriteLine();
list.Sort();
for (int i = 0; i < list.Count; i++)
Console.Write(list[i] + " ");
Console.WriteLine();
while (!list.IsEmpty)
{
int v = list.PopBack();
Console.Write(v + " ");
}
Console.ReadKey(true);
}
}public static void Main()
{
const int n = 20;
MyCollections.LinkedList<int> list = new MyCollections.LinkedList<int>();
int val = 0;
int pos = 0;
string yn = "y";
Console.WriteLine("Ввод чисел:");
for (int i = 1; i <= n; ++i)
list.AddBack(int.Parse(Console.ReadLine()));
/*Console.Write("Число для вставки в список: ");
val = int.Parse(Console.ReadLine());
Console.Write("Позиция для вставки: ");
pos = int.Parse(Console.ReadLine()) - 1;*/
// yn = "y";
while(yn == "y")
{
Console.Write("Число для вставки в список: ");
val = int.Parse(Console.ReadLine());
Console.Write("Позиция для вставки: ");
pos = int.Parse(Console.ReadLine()) - 1;
list.Insert(pos, val);
foreach (int item in list)
Console.Write("{0} ", item);
Console.ReadLine();
Console.Write("Продолжить? y/n ");
yn = Console.ReadLine();Решение задачи: «Вставка нового узла в бинарное дерево»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication188
{
class Program
{
static void Main(string[] args)
{
Node<int> root = new Node<int>{Data = 1};
while(true)
{
Console.Clear();
Console.WriteLine("Tree:");
Console.BackgroundColor = ConsoleColor.DarkGray;
Console.WriteLine(root.ToStringTree() + "\r\n");
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("1 Add Left");
Console.WriteLine("2 Add Right");
Console.WriteLine("3 Remove");
Console.WriteLine("4 Get parent");
Console.WriteLine("5 Get Left");
Console.WriteLine("6 Get Right");
Console.WriteLine("9 Exit");
Console.ForegroundColor = ConsoleColor.Gray;
var command = ReadInt();
if (command == 9) break;
int data = ReadInt("Enter data of node: ");
var node = root.GetThisAndAllChilds(d => d == data).FirstOrDefault();
if (node == null)
WriteAndWait("Node is not found");
else
switch(command)
{
case 1: node.InsertLeft(new Node<int> { Data = ReadInt("Enter data of new child node: ") }); break;
case 2: node.InsertRight(new Node<int> { Data = ReadInt("Enter data of new child node: ") }); break;
case 3: if(node.Parent != null) node.Parent.DeleteChild(node); break;
case 4: if (node.Parent != null) WriteAndWait("Parent: " + node.Parent); break;
case 5: if (node.Left != null) WriteAndWait("Left: " + node.Left); break;
case 6: if (node.Right != null) WriteAndWait("Right: " + node.Right); break;
}
}
}
private static void WriteAndWait(string str)
{
Console.WriteLine(str);
Console.Write("(press any key to continue...)");
Console.ReadKey();
}
static int ReadInt(string title = "")
{
if(title != null)
Console.Write(title);
int res = 0;
while(true)
if (int.TryParse(Console.ReadLine(), out res))
return res;
}
}
class Node<T>
{
public Node<T> Parent { get; private set; }
public Node<T> Left { get; private set; }
public Node<T> Right { get; private set; }
public T Data { get; set; }
public void InsertRight(Node<T> node)
{
node.Right = Right;
Right = node;
node.Parent = this;
}
public void InsertLeft(Node<T> node)
{
node.Left = Left;
Left = node;
node.Parent = this;
}
public void DeleteChild(Node<T> node)
{
if (Right == node) Right = null;
if (Left == node) Left = null;
node.Parent = null;
}
public IEnumerable<Node<T>> GetThisAndAllChilds(Predicate<T> condition = null)
{
if(condition == null || condition(Data))
yield return this;
if (Right != null)
foreach (var n in Right.GetThisAndAllChilds(condition))
yield return n;
if (Left != null)
foreach (var n in Left.GetThisAndAllChilds(condition))
yield return n;
}
public override string ToString()
{
return Data.ToString();
}
public string ToStringTree(int indent = 0)
{
var sb = new StringBuilder();
sb.AppendLine(new String(' ', indent) + ToString());
if (Right != null)
sb.Append(Right.ToStringTree(indent + 1));
if (Left != null)
sb.Append(Left.ToStringTree(indent + 1));
return sb.ToString();
}
}
}