Advertisement
Vanya_Shestakov

Untitled

Mar 15th, 2021 (edited)
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.47 KB | None | 0 0
  1. package com.company.struct;
  2.  
  3. public class Node {
  4.     private int data;
  5.     private Node leftChild;
  6.     private Node rightChild;
  7.  
  8.     public Node(int data) {
  9.         this.data = data;
  10.     }
  11.  
  12.     public void setLeftChild(Node leftChild) {
  13.         this.leftChild = leftChild;
  14.     }
  15.  
  16.     public void setRightChild(Node rightChild) {
  17.         this.rightChild = rightChild;
  18.     }
  19.  
  20.     public Node getLeftChild() {
  21.         return this.leftChild;
  22.     }
  23.  
  24.     public Node getRightChild() {
  25.         return this.rightChild;
  26.     }
  27.  
  28.     public int getData() {
  29.         return this.data;
  30.     }
  31.  
  32.     public void outputNode() {
  33.         System.out.print(this.data + " ");
  34.     }
  35. }
  36.  
  37.  
  38.  
  39. package com.company.struct;
  40.  
  41. import java.io.FileWriter;
  42. import java.io.IOException;
  43. import java.util.Stack;
  44.  
  45. public class Tree {
  46.     private Node root = null;
  47.  
  48.     public Tree() {
  49.     }
  50.  
  51.     public Node getRoot() {
  52.         return this.root;
  53.     }
  54.  
  55.     public Node find(int key) {
  56.         Node current = this.root;
  57.  
  58.         do {
  59.             if (current.getData() == key) {
  60.                 return current;
  61.             }
  62.  
  63.             if (key < current.getData()) {
  64.                 current = current.getLeftChild();
  65.             } else {
  66.                 current = current.getRightChild();
  67.             }
  68.         } while(current != null);
  69.  
  70.         return null;
  71.     }
  72.  
  73.     public void insert(int data) {
  74.         Node newNode = new Node(data);
  75.         if (this.root == null) {
  76.             this.root = newNode;
  77.         } else {
  78.             Node current = this.root;
  79.  
  80.             Node parent;
  81.             label21:
  82.             do {
  83.                 do {
  84.                     parent = current;
  85.                     if (data < current.getData()) {
  86.                         current = current.getLeftChild();
  87.                         continue label21;
  88.                     }
  89.  
  90.                     current = current.getRightChild();
  91.                 } while(current != null);
  92.  
  93.                 parent.setRightChild(newNode);
  94.                 return;
  95.             } while(current != null);
  96.  
  97.             parent.setLeftChild(newNode);
  98.         }
  99.     }
  100.  
  101.     private Node getSuccessor(Node delNode) {
  102.         Node successorParent = delNode;
  103.         Node successor = delNode;
  104.  
  105.         for(Node current = delNode.getRightChild(); current != null; current = current.getLeftChild()) {
  106.             successorParent = successor;
  107.             successor = current;
  108.         }
  109.  
  110.         if (successor != delNode.getRightChild()) {
  111.             successorParent.setLeftChild(successor.getRightChild());
  112.             successor.setRightChild(delNode.getRightChild());
  113.         }
  114.  
  115.         return successor;
  116.     }
  117.  
  118.     public void delete(int data) {
  119.         Node current = this.root;
  120.         Node parent = this.root;
  121.         boolean isLeftChild = true;
  122.  
  123.         while(current.getData() != data) {
  124.             parent = current;
  125.             if (data < current.getData()) {
  126.                 isLeftChild = true;
  127.                 current = current.getLeftChild();
  128.             } else {
  129.                 isLeftChild = false;
  130.                 current = current.getRightChild();
  131.             }
  132.  
  133.             if (current == null) {
  134.                 return;
  135.             }
  136.         }
  137.  
  138.         if (current.getLeftChild() == null && current.getRightChild() == null) {
  139.             if (current == this.root) {
  140.                 this.root = null;
  141.             } else if (isLeftChild) {
  142.                 parent.setLeftChild((Node)null);
  143.             } else {
  144.                 parent.setRightChild((Node)null);
  145.             }
  146.         } else if (current.getRightChild() == null) {
  147.             if (current == this.root) {
  148.                 this.root = current.getLeftChild();
  149.             } else if (isLeftChild) {
  150.                 parent.setLeftChild(current.getLeftChild());
  151.             } else {
  152.                 parent.setRightChild(current.getLeftChild());
  153.             }
  154.         } else if (current.getLeftChild() == null) {
  155.             if (current == this.root) {
  156.                 this.root = current.getRightChild();
  157.             } else if (isLeftChild) {
  158.                 parent.setLeftChild(current.getRightChild());
  159.             } else {
  160.                 parent.setRightChild(current.getRightChild());
  161.             }
  162.         } else {
  163.             Node successor = this.getSuccessor(current);
  164.             if (current == this.root) {
  165.                 this.root = successor;
  166.             } else if (isLeftChild) {
  167.                 parent.setLeftChild(successor);
  168.             } else {
  169.                 parent.setRightChild(successor);
  170.             }
  171.  
  172.             successor.setLeftChild(current.getLeftChild());
  173.         }
  174.  
  175.     }
  176.  
  177.     public void postOrder(Node localRoot) {
  178.         if (localRoot != null) {
  179.             this.postOrder(localRoot.getLeftChild());
  180.             this.postOrder(localRoot.getRightChild());
  181.             localRoot.outputNode();
  182.         }
  183.  
  184.     }
  185.  
  186.     public void outputInFile(String patch) throws IOException {
  187.         FileWriter writer = new FileWriter(patch);
  188.         Stack globalStack = new Stack();
  189.         globalStack.push(this.root);
  190.         int nBlanks = 32;
  191.         boolean isRowEmpty = false;
  192.         writer.write("****************************************************************\n");
  193.         writer.write("                         Бинарное дерево\n");
  194.  
  195.         while(!isRowEmpty) {
  196.             Stack localStack = new Stack();
  197.             isRowEmpty = true;
  198.  
  199.             for(int j = 0; j < nBlanks; ++j) {
  200.                 writer.write(32);
  201.             }
  202.  
  203.             while(!globalStack.isEmpty()) {
  204.                 Node temp = (Node)globalStack.pop();
  205.                 if (temp != null) {
  206.                     writer.write(Integer.toString(temp.getData()));
  207.                     localStack.push(temp.getLeftChild());
  208.                     localStack.push(temp.getRightChild());
  209.                     if (temp.getLeftChild() != null || temp.getRightChild() != null) {
  210.                         isRowEmpty = false;
  211.                     }
  212.                 } else {
  213.                     writer.write("--");
  214.                     localStack.push((Object)null);
  215.                     localStack.push((Object)null);
  216.                 }
  217.  
  218.                 for(int j = 0; j < nBlanks * 2 - 2; ++j) {
  219.                     writer.write(32);
  220.                 }
  221.             }
  222.  
  223.             writer.write("\n");
  224.             nBlanks /= 2;
  225.  
  226.             while(!localStack.isEmpty()) {
  227.                 globalStack.push(localStack.pop());
  228.             }
  229.         }
  230.  
  231.         writer.write("\n****************************************************************");
  232.         writer.flush();
  233.     }
  234.  
  235.     public void displayTree() {
  236.         Stack globalStack = new Stack();
  237.         globalStack.push(this.root);
  238.         int nBlanks = 32;
  239.         boolean isRowEmpty = false;
  240.         System.out.println("****************************************************************");
  241.         System.out.println("                         Бинарное дерево");
  242.  
  243.         while(!isRowEmpty) {
  244.             Stack localStack = new Stack();
  245.             isRowEmpty = true;
  246.  
  247.             for(int j = 0; j < nBlanks; ++j) {
  248.                 System.out.print(' ');
  249.             }
  250.  
  251.             while(!globalStack.isEmpty()) {
  252.                 Node temp = (Node)globalStack.pop();
  253.                 if (temp != null) {
  254.                     System.out.print(temp.getData());
  255.                     localStack.push(temp.getLeftChild());
  256.                     localStack.push(temp.getRightChild());
  257.                     if (temp.getLeftChild() != null || temp.getRightChild() != null) {
  258.                         isRowEmpty = false;
  259.                     }
  260.                 } else {
  261.                     System.out.print("--");
  262.                     localStack.push((Object)null);
  263.                     localStack.push((Object)null);
  264.                 }
  265.  
  266.                 for(int j = 0; j < nBlanks * 2 - 2; ++j) {
  267.                     System.out.print(' ');
  268.                 }
  269.             }
  270.  
  271.             System.out.println();
  272.             nBlanks /= 2;
  273.  
  274.             while(!localStack.isEmpty()) {
  275.                 globalStack.push(localStack.pop());
  276.             }
  277.         }
  278.  
  279.         System.out.println("****************************************************************");
  280.     }
  281.  
  282.     public void clear() {
  283.         this.root = null;
  284.     }
  285.  
  286.     public int getDiameter(Node root) {
  287.         if (root == null) {
  288.             return 0;
  289.         } else {
  290.             int rootDiameter = this.getHeight(root.getLeftChild()) + this.getHeight(root.getRightChild()) + 1;
  291.             int leftDiameter = this.getDiameter(root.getLeftChild());
  292.             int rightDiameter = this.getDiameter(root.getRightChild());
  293.             return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
  294.         }
  295.     }
  296.  
  297.     public int getHeight(Node root) {
  298.         return root == null ? 0 : Math.max(this.getHeight(root.getLeftChild()), this.getHeight(root.getRightChild())) + 1;
  299.     }
  300. }
  301.  
  302.  
  303. package com.company.starter;
  304.  
  305. import com.company.struct.Tree;
  306.  
  307. import java.io.File;
  308. import java.io.FileNotFoundException;
  309. import java.io.IOException;
  310. import java.util.Scanner;
  311.  
  312. public class Main {
  313.  
  314.     static Scanner scannerConsole;
  315.     static Tree treeInt;
  316.  
  317.     static final int CREATE_TREE = 1;
  318.     static final int OPEN_TREE = 2;
  319.     static final int ADD_NODE = 1;
  320.     static final int DELETE_NODE = 2;
  321.     static final int VIEW_TREE = 3;
  322.     static final int MAX_WAY = 4;
  323.     static final int POST_ORDER = 5;
  324.     static final int SAVE_TREE_OF_MENU = 6;
  325.     static final int OPEN_TREE_OF_MENU = 7;
  326.     static final int EXIT_PROGRAM = 0;
  327.  
  328.     static int enterValue(){
  329.         int num;
  330.         boolean isCorrect = true;
  331.         num = 0;
  332.         do {
  333.             try {
  334.                 num = Integer.parseInt(scannerConsole.nextLine());
  335.                 isCorrect = false;
  336.             } catch (Exception E) {
  337.                 System.out.print("Ошибка, повторите ввод: ");
  338.             }
  339.         } while(isCorrect);
  340.         return num;
  341.     }
  342.  
  343.     static int enterNodeForAdd(){
  344.         int num;
  345.         boolean isCorrect;
  346.         do{
  347.             isCorrect = false;
  348.             num = enterValue();
  349.             if(treeInt.getRoot() != null)
  350.                 if(treeInt.find(num) != null){
  351.                     System.out.print("Данное число уже есть в дереве. Повторите ввод: ");
  352.                     isCorrect = true;
  353.                 }
  354.         }while(isCorrect);
  355.         return num;
  356.     }
  357.  
  358.     static int enterNodeForDel(){
  359.         int num;
  360.         boolean isCorrect;
  361.         do{
  362.             isCorrect = false;
  363.             num = enterValue();
  364.             if(treeInt.find(num) == null){
  365.                 System.out.print("Данного числа нет в дереве. Повторите ввод: ");
  366.                 isCorrect = true;
  367.             }
  368.         }while(isCorrect);
  369.         return num;
  370.     }
  371.  
  372.     static boolean isCorrectChoice(int choice){
  373.         boolean isInCorrect;
  374.         if(choice == CREATE_TREE || choice == OPEN_TREE){
  375.             isInCorrect = false;
  376.         }
  377.         else{
  378.             isInCorrect = true;
  379.         }
  380.         return isInCorrect;
  381.     }
  382.  
  383.     static void printSelection(boolean isInCorrect, int choice){
  384.         if(!isInCorrect){
  385.             System.out.println("Вы выбрали вариант " + choice);
  386.             System.out.println("---------------------------------------------");
  387.         }
  388.         else {
  389.             System.out.print("Пожалуйста, выберите указанные варианты: ");
  390.         }
  391.     }
  392.  
  393.     static int getTheChoice(){
  394.         int choice;
  395.         boolean isInCorrect;
  396.         do {
  397.             choice = enterValue();
  398.             isInCorrect = isCorrectChoice(choice);
  399.             printSelection(isInCorrect, choice);
  400.         }while(isInCorrect);
  401.         return choice;
  402.     }
  403.  
  404.     static boolean isCorrectSizeFile(String patch) {
  405.         boolean isCorrect = true;
  406.         File inputFile = new File(patch);
  407.         if (inputFile.length() == 0) {
  408.             System.out.print("Файл пустой, повторите ввод: ");
  409.             isCorrect = false;
  410.         }
  411.         return isCorrect;
  412.     }
  413.  
  414.     static boolean isFileCorrect(String patch) throws IOException {
  415.         Scanner scannerFile = new Scanner(new File(patch));
  416.         boolean isCorrect = true;
  417.         while(scannerFile.hasNextLine() && isCorrect){
  418.             try {
  419.                 scannerFile.nextInt();
  420.             } catch(Exception E) {
  421.                 System.out.print("Данные в указанном файле не соответсвуют условию. Повторите ввод: ");
  422.                 isCorrect = false;
  423.             }
  424.         }
  425.         scannerFile.close();
  426.         return isCorrect;
  427.     }
  428.  
  429.     static boolean IsFileExist(String patch){
  430.         boolean isCorrect;
  431.         File inputFile = new File(patch);
  432.         if (inputFile.exists()){
  433.             isCorrect = true;
  434.         }
  435.         else{
  436.             isCorrect = false;
  437.             System.out.print("Указанного файла не существует. Повторите ввод: ");
  438.         }
  439.         return isCorrect;
  440.     }
  441.  
  442.     static String enterPatch() throws IOException {
  443.         String patch;
  444.         boolean isCorrect;
  445.         System.out.print("Введите адрес файла: ");
  446.         do {
  447.             patch = scannerConsole.nextLine();
  448.             isCorrect = (IsFileExist(patch) && isCorrectSizeFile(patch) && isFileCorrect(patch));
  449.         } while (!isCorrect);
  450.         return patch;
  451.     }
  452.  
  453.     static void fillTreeFromFile(String patch) throws FileNotFoundException {
  454.         Scanner scannerFile = new Scanner(new File(patch));
  455.         int temp;
  456.         while(scannerFile.hasNextLine()){
  457.             temp = scannerFile.nextInt();
  458.             treeInt.insert(temp);
  459.         }
  460.         scannerFile.close();
  461.     }
  462.  
  463.     static void openTreeFromFile() throws IOException {
  464.         treeInt.clear();
  465.         System.out.println("Открытие дерева");
  466.         System.out.println("---------------------------------------------");
  467.         String patch = enterPatch();
  468.         fillTreeFromFile(patch);
  469.     }
  470.  
  471.     static void openTree(int choice) throws IOException, ClassNotFoundException {
  472.         if(choice == OPEN_TREE){
  473.             openTreeFromFile();
  474.         }
  475.     }
  476.  
  477.     static boolean isCorrectChoiceForMenu(int choice){
  478.         boolean isCorrect;
  479.         if(choice == ADD_NODE || choice == DELETE_NODE || choice == VIEW_TREE
  480.                 || choice == MAX_WAY || choice == POST_ORDER || choice == SAVE_TREE_OF_MENU
  481.                 || choice == OPEN_TREE_OF_MENU || choice == EXIT_PROGRAM){
  482.             isCorrect = false;
  483.         }
  484.         else{
  485.             isCorrect = true;
  486.         }
  487.         return isCorrect;
  488.     }
  489.  
  490.     static int inputTheChoiceForMenu(){
  491.         int choice;
  492.         boolean isCorrect;
  493.         do {
  494.             choice = enterValue();
  495.             isCorrect = isCorrectChoiceForMenu(choice);
  496.             printSelection(isCorrect, choice);
  497.         }while(isCorrect);
  498.         return choice;
  499.     }
  500.  
  501.     static void printMainMenu(){
  502.         System.out.println("\nПрограмма работы с бинарным деревом");
  503.         System.out.println("---------------------------------------");
  504.         System.out.print("Построить дерево(1) \nОткрыть дерево из файла(2)\n\nВвод: ");
  505.     }
  506.  
  507.     static void printInfoMenu(){
  508.         System.out.println("---------------------------------------------");
  509.         System.out.println("\t\t\tБинарное дерево");
  510.         System.out.println("---------------------------------------------");
  511.         System.out.println("Выберите действие, которое вы хотите выполнить:");
  512.         System.out.println("(1)Добавление элемента");
  513.         System.out.println("(2)Удаление указанного элемента");
  514.         System.out.println("(3)Просмотр элементов дерева");
  515.         System.out.println("(4)Максимальный путь");
  516.         System.out.println("(5)Обратный обход дерева");
  517.         System.out.println("(6)Сохранение дерева");
  518.         System.out.println("(7)Открыть дерево");
  519.         System.out.println("(0)Выход");
  520.         System.out.print("Ввод: ");
  521.     }
  522.  
  523.     static void addNode() throws IOException, ClassNotFoundException {
  524.         System.out.println("Добавление элемента в дерево");
  525.         System.out.println("------------------------------");
  526.         System.out.print("Введите число, которое хотите добавить: ");
  527.         int num = enterNodeForAdd();
  528.         treeInt.insert(num);
  529.         System.out.println("Число " + num + " успешно добавлено");
  530.         selectionMenu();
  531.     }
  532.  
  533.  
  534.  
  535.     static void deleteNode() throws IOException, ClassNotFoundException {
  536.         if(treeInt.getRoot() == null){
  537.             System.out.println("Дерево пусто");
  538.         } else {
  539.             System.out.println("Удаление элемента из дерева");
  540.             System.out.println("------------------------------");
  541.             System.out.print("Введите число, которое хотите удалить: ");
  542.             int num = enterNodeForDel();
  543.             treeInt.delete(num);
  544.             System.out.println("Число " + num + " успешно удалено");
  545.         }
  546.     }
  547.  
  548.     static void viewTree(){
  549.         if(treeInt.getRoot() != null){
  550.             treeInt.displayTree();
  551.             System.out.print("\n");
  552.         } else {
  553.             System.out.println("Дерево пусто");
  554.         }
  555.     }
  556.  
  557.     static void saveTree() throws IOException {
  558.         System.out.println("\t\t\tСохранение дерева");
  559.         System.out.println("---------------------------------------------");
  560.         System.out.print("Введите адрес: ");
  561.         String patch = scannerConsole.nextLine();
  562.         treeInt.outputInFile(patch);
  563.         System.out.println("Данные записаны в файл с адресом: " + patch);
  564.     }
  565.  
  566.     static void checkSizeTreeForSave() throws IOException {
  567.         if(treeInt.getRoot() == null){
  568.             System.out.println("Дерево пусто");
  569.         } else {
  570.             saveTree();
  571.         }
  572.     }
  573.  
  574.     static void postOrder(){
  575.         if(treeInt.getRoot() == null){
  576.             System.out.println("Дерево пусто");
  577.         } else {
  578.             System.out.print("Обратный обход дерева: ");
  579.             treeInt.postOrder(treeInt.getRoot());
  580.             System.out.println("\n");
  581.         }
  582.     }
  583.  
  584.     static void maxWay(){
  585.         if(treeInt.getRoot() == null){
  586.             System.out.println("Дерево пусто");
  587.         } else {
  588.             System.out.print("Путь максимальной длины между вершинами с разным числом потомков равен:  ");
  589.             System.out.println(treeInt.getDiameter(treeInt.getRoot()) - 1);
  590.         }
  591.     }
  592.  
  593.     static void selectionMenu()  throws IOException, ClassNotFoundException {
  594.         printInfoMenu();
  595.         switch (inputTheChoiceForMenu()){
  596.             case ADD_NODE:
  597.                 addNode();
  598.                 selectionMenu();
  599.             case DELETE_NODE:
  600.                 deleteNode();
  601.                 selectionMenu();
  602.             case VIEW_TREE:
  603.                 viewTree();
  604.                 selectionMenu();
  605.             case MAX_WAY:
  606.                 maxWay();
  607.                 selectionMenu();
  608.             case POST_ORDER:
  609.                 postOrder();
  610.                 selectionMenu();
  611.             case SAVE_TREE_OF_MENU:
  612.                 checkSizeTreeForSave();
  613.                 selectionMenu();
  614.             case OPEN_TREE_OF_MENU:
  615.                 openTreeFromFile();
  616.                 selectionMenu();
  617.             case EXIT_PROGRAM:
  618.                 System.out.println("Конец программы");
  619.                 System.exit(0);
  620.         }
  621.     }
  622.  
  623.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  624.         scannerConsole = new Scanner(System.in);
  625.         treeInt = new Tree();
  626.         printMainMenu();
  627.         openTree(getTheChoice());
  628.         selectionMenu();
  629.         scannerConsole.close();
  630.     }
  631. }
  632.  
  633.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement