Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class main
- {
- public static void Main()
- {
- BinaryTree tr1 = new BinaryTree();
- using (StreamReader fileIn = new StreamReader(@"C:\Users\lexpr\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\input.txt"))
- {
- string line = fileIn.ReadToEnd();
- string[] data = line.Split(' ');
- foreach (string item in data)
- {
- tr1.Add(int.Parse(item));
- }
- }
- tr1.Preorder();
- }
- }
- /****************************************************************************************************/
- public class BinaryTree
- {
- public class Node
- {
- public object inf; //информационное поле
- public Node left; //ссылка на левое поддерево
- public Node rigth; //ссылка на правое поддерево
- //конструктор вложенного класса, создает узел дерева
- public Node(object nodeInf)
- {
- inf = nodeInf;
- left = null;
- rigth = null;
- }
- //добавляет узел в дерево так, чтобы дерево оставалось деревом бинарного поиска
- public static void Add(ref Node r, object nodeInf)
- {
- if (r == null)
- {
- r = new Node(nodeInf);
- }
- else
- {
- if (((IComparable)(r.inf)).CompareTo(nodeInf) > 0)
- {
- Add(ref r.left, nodeInf);
- }
- else
- {
- Add(ref r.rigth, nodeInf);
- }
- }
- }
- public static int Preorder(Node r) //прямой обход дерева
- {
- int count = 0;
- if (r != null)
- {
- Console.Write("{0} ", r.inf);
- if ((int)r.inf % 2 == 0) { count++;};
- count += Preorder(r.left);
- count += Preorder(r.rigth);
- }
- Console.Write(count);
- return count;
- }
- private static void Del(Node t, ref Node tr)
- {
- if (tr.rigth != null)
- {
- Del(t, ref tr.rigth);
- }
- else
- {
- t.inf = tr.inf;
- tr = tr.left;
- }
- }
- public static void Delete(ref Node t, object key)
- {
- if (t == null)
- {
- throw new Exception("Данное значение в дереве отсутствует");
- }
- else
- {
- if (((IComparable)(t.inf)).CompareTo(key) > 0)
- {
- Delete(ref t.left, key);
- }
- else
- {
- if (((IComparable)(t.inf)).CompareTo(key) < 0)
- {
- Delete(ref t.rigth, key);
- }
- else
- {
- if (t.left == null)
- {
- t = t.rigth;
- }
- else
- {
- if (t.rigth == null)
- {
- t = t.left;
- }
- else
- {
- Node tr = t.left;
- Del(t, ref tr);
- }
- }
- }
- }
- }
- }
- }
- Node tree; //ссылка на корень дерева
- //свойство позволяет получить доступ к значению информационного поля корня дерева
- public object Inf
- {
- set
- {
- tree.inf = value;
- }
- get
- {
- return tree.inf;
- }
- }
- public BinaryTree()
- {
- tree = null;
- }
- private BinaryTree(Node r)
- {
- tree = r;
- }
- public void Add(object nodeInf) //добавление узла в дерево
- {
- Node.Add(ref tree, nodeInf);
- }
- public void Preorder()
- {
- Node.Preorder(tree);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment