Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- namespace Program
- {
- class Program
- {
- static void Main()
- {
- BinaryTree tree = new BinaryTree();
- using (StreamReader fileIn = new StreamReader("C:/Users/Acer/Desktop/input.txt"))
- {
- string line = fileIn.ReadToEnd();
- string[] data = line.Split(' ');
- foreach (string item in data)
- {
- tree.Add(int.Parse(item));
- }
- }
- Console.WriteLine("Прямой обход:");
- tree.Preorder();
- Console.WriteLine("Симметричный обход:");
- tree.Inorder();
- Console.WriteLine("Обратный обход:");
- tree.Postorder();
- Console.Write("Введите целое число k (k >= 1): ");
- int k = int.Parse(Console.ReadLine());
- Console.WriteLine("Кол-во узлов на k-ом уровне дерева равно: {0}", tree.countOfNodes(k));
- }
- };
- public class BinaryTree
- {
- private class Node
- {
- public object inf; // инф. часть
- public Node left; // ссылка на лев. поддерево
- public Node right; // ссылка на прав. поддерево
- // конструктор (создание узла)
- public Node(object nodeInf)
- {
- inf = nodeInf;
- left = null;
- right = 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.right, nodeInf);
- }
- // подсчет узлов в дереве, расположенных на k-ом уровне
- public static int countOfNodes(Node r, int l)
- {
- if (r == null) return 0;
- else if (l == 1) return 1;
- else return countOfNodes(r.left, l - 1) + countOfNodes(r.right, l - 1);
- }
- // прямой обход
- public static void Preorder(Node r)
- {
- if (r != null)
- {
- Console.Write("{0} ", r.inf);
- Preorder(r.left);
- Preorder(r.right);
- }
- }
- // симметричный обход
- public static void Inorder(Node r)
- {
- if (r != null)
- {
- Inorder(r.left);
- Console.Write("{0} ", r.inf);
- Inorder(r.right);
- }
- }
- // обратный обход
- public static void Postorder(Node r)
- {
- if (r != null)
- {
- Postorder(r.left);
- Postorder(r.right);
- Console.Write("{0} ", r.inf);
- }
- }
- };
- Node tree; // ссылка на корень
- // конструктор (создание дерева)
- public BinaryTree()
- {
- tree = null;
- }
- public void Add(object nodeInf)
- {
- Node.Add(ref tree, nodeInf);
- }
- public int countOfNodes(int l)
- {
- return Node.countOfNodes(tree, l);
- }
- public void Preorder()
- {
- Node.Preorder(tree);
- Console.Write("\n");
- }
- public void Inorder()
- {
- Node.Inorder(tree);
- Console.Write("\n");
- }
- public void Postorder()
- {
- Node.Postorder(tree);
- Console.Write("\n");
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement