Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- namespace ConsoleApp1
- {
- 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));
- }
- }
- tree.Inorder();
- if (tree.isBalanced()) Console.WriteLine("Дерево является сбалансированным");
- else Console.WriteLine("Дерево не является сбалансированным");
- tree.Delete(15);
- tree.Inorder();
- }
- };
- public class BinaryTree
- {
- private class Node
- {
- public object inf;
- public int height;
- public Node left, right;
- public Node(object nodeInf)
- {
- inf = nodeInf;
- height = 0;
- left = right = null;
- }
- public static int Height(Node r)
- {
- int heightLeft = (r.left != null) ? r.left.height : -1;
- int heightRight = (r.right != null) ? r.right.height : -1;
- return Math.Max(heightLeft, heightRight) + 1;
- }
- public static void Add(ref Node r, object nodeInf)
- {
- if (r == null) r = new Node(nodeInf);
- else
- {
- if (((IComparable)(nodeInf)).CompareTo(r.inf) < 0) Add(ref r.left, nodeInf);
- else Add(ref r.right, nodeInf);
- r.height = Height(r);
- }
- }
- public static bool isBalanced(Node r)
- {
- if (r == null) return true;
- else
- {
- int heightLeft = (r.left != null) ? r.left.height : -1;
- int heightRight = (r.right != null) ? r.right.height : -1;
- if (Math.Abs(heightLeft - heightRight) > 1) return false;
- else return isBalanced(r.left) && isBalanced(r.right);
- }
- }
- public static void Inorder(Node r)
- {
- if (r != null)
- {
- Inorder(r.left);
- Console.Write("({0}, {1}) ", r.inf, r.height);
- Inorder(r.right);
- }
- }
- private static void Del(Node t, ref Node tr)
- {
- if (tr.right != null)
- {
- Del(t, ref tr.right);
- tr.height = Height(tr);
- }
- 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)(key)).CompareTo(t.inf) < 0)
- {
- Delete(ref t.left, key);
- t.height = Height(t);
- }
- else if (((IComparable)(key)).CompareTo(t.inf) > 0)
- {
- Delete(ref t.right, key);
- t.height = Height(t);
- }
- else
- {
- if (t.left == null) t = t.right;
- else if (t.right == null) t = t.left;
- else
- {
- Del(t, ref t.left);
- t.height = Height(t);
- }
- }
- }
- };
- Node tree;
- public BinaryTree() { tree = null; }
- public void Add(object nodeInf)
- {
- Node.Add(ref tree, nodeInf);
- }
- public bool isBalanced()
- {
- return Node.isBalanced(tree);
- }
- public void Inorder()
- {
- Node.Inorder(tree);
- Console.Write("\n");
- }
- public void Delete(object key)
- {
- Node.Delete(ref tree, key);
- }
- };
- }
Add Comment
Please, Sign In to add comment