Advertisement
Alyks

Untitled

Apr 17th, 2020
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.98 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.FileReader;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.Scanner;
  8.  
  9. class BinaryTree {
  10.     Node root = null;
  11.  
  12.     Node addToTree(Node node, double value) {
  13.         if(node == null) {
  14.             Node root = new Node(value);
  15.             root.path.add(root);
  16.             return root;
  17.         }
  18.  
  19.         if(value < node.value) {
  20.             if(node.left == null) {
  21.                 node.left = new Node(value);
  22.                 node.left.path.addAll(node.path);
  23.                 node.left.path.add(node.left);
  24.             } else {
  25.                 addToTree(node.left, value);
  26.             }
  27.         } else if(value > node.value) {
  28.             if(node.right == null) {
  29.                 node.right = new Node(value);
  30.                 node.right.path.addAll(node.path);
  31.                 node.right.path.add(node.right);
  32.             } else {
  33.                 addToTree(node.right, value);
  34.             }
  35.         }
  36.  
  37.         return node;
  38.     }
  39.  
  40.     void removeVertex(Node node) {
  41.         int size = node.path.size();
  42.         if(size - 2 > -1) {
  43.             Node parent = node.path.get(size-2);
  44.             if(parent.left == node)
  45.                 parent.left = null;
  46.             else if(parent.right == node)
  47.                 parent.right = null;
  48.         }
  49.     }
  50.  
  51.     boolean contains(double value, Node node) {
  52.         if(node == null)
  53.             return false;
  54.  
  55.         if(value == node.value)
  56.             return true;
  57.  
  58.         if(value < node.value)
  59.             return contains(value, node.left);
  60.         else if(value > node.value)
  61.             return contains(value, node.right);
  62.  
  63.         return false;
  64.     }
  65.  
  66.     String takeVisual() {
  67.         if(root == null)
  68.            return "Невозможно отобразить пустое дерево";
  69.  
  70.         StringBuilder tree = new StringBuilder();
  71.         tree.append(root.value);
  72.         String pointerLeft;
  73.         if (root.right != null)
  74.             pointerLeft = "+--";
  75.         else
  76.             pointerLeft = "L--";
  77.  
  78.         takeNodesString(tree, "", pointerLeft, root.left, root.right != null);
  79.         takeNodesString(tree, "", "L--", root.right, false);
  80.         return tree.toString();
  81.     }
  82.  
  83.     void takeNodesString(StringBuilder tree, String padding, String pointer, Node node, boolean hasRightNode) {
  84.         if (node != null) {
  85.             tree.append("\n").append(padding).append(pointer).append(node.value < 0 ? "(" + node.value + ")" : node.value);
  86.             if (hasRightNode)
  87.                 padding += "¦  ";
  88.             else
  89.                 padding += "   ";
  90.  
  91.             if (node.right != null)
  92.                 pointer = "+--";
  93.             else
  94.                 pointer = "L--";
  95.  
  96.             takeNodesString(tree, padding, pointer, node.left, node.right != null);
  97.             takeNodesString(tree, padding, "L--", node.right, false);
  98.         }
  99.     }
  100.  
  101.     ArrayList<Node> maxPathRecursive(Node node, ArrayList<Node> path) {
  102.         if(node == null)
  103.             return path;
  104.         ArrayList<Node> maxPath = new ArrayList<>();
  105.         if(node.path.size() > maxPath.size())
  106.             maxPath = node.path;
  107.         ArrayList<Node> leftPath = maxPathRecursive(node.left, maxPath);
  108.         ArrayList<Node> rightPath = maxPathRecursive(node.right, maxPath);
  109.         if(leftPath.size() > rightPath.size())
  110.             maxPath = leftPath;
  111.         else
  112.             maxPath = rightPath;
  113.         return maxPath;
  114.     }
  115.  
  116.     ArrayList<Node> maxPath() {
  117.         return maxPathRecursive(root, root.path);
  118.     }
  119.  
  120.     void add(double value) {
  121.         root = addToTree(root, value);
  122.     }
  123. }
  124.  
  125. class Node {
  126.     double value;
  127.     Node left = null;
  128.     Node right = null;
  129.     ArrayList<Node> path = new ArrayList<>();
  130.     Node(double value) {
  131.         this.value = value;
  132.     }
  133. }
  134.  
  135. public class Main {
  136.     static BinaryTree inputTreeFromConsole(Scanner scan) {
  137.         boolean continueCycle = true;
  138.         int i = 1;
  139.         BinaryTree tree = new BinaryTree();
  140.         System.out.println("Введите [стоп], если хотите прекратить ввод");
  141.         while(continueCycle) {
  142.             boolean notCorrect = true;
  143.             while(notCorrect) {
  144.                 System.out.println("Введите " + i + "-ю вершину дерева");
  145.                 String value = scan.nextLine();
  146.                 if(value.equals("стоп")) {
  147.                     continueCycle = false;
  148.                     notCorrect = false;
  149.                 } else {
  150.                     try {
  151.                         double elem = Double.parseDouble(value);
  152.                         if(!tree.contains(elem, tree.root)) {
  153.                             tree.add(elem);
  154.                             notCorrect = false;
  155.                         } else {
  156.                             System.out.println("Такая вершина уже существует, повторите ввод");
  157.                         }
  158.                     } catch (Exception err) {
  159.                         System.out.println("Вершина дерева должна быть вещественным числом, повторите ввод");
  160.                     }
  161.                 }
  162.             }
  163.             i++;
  164.         }
  165.         return tree;
  166.     }
  167.  
  168.     static BinaryTree inputTreeFromFile(Scanner scan) {
  169.         String filePath = "";
  170.         boolean notCorrect = true;
  171.         BinaryTree tree = new BinaryTree();
  172.         while(notCorrect) {
  173.             System.out.println("Введите путь к файлу");
  174.             filePath = scan.nextLine();
  175.             try(FileReader fr = new FileReader(filePath)) {
  176.                 Scanner frScan = new Scanner(fr);
  177.                 String nums = frScan.nextLine().trim();
  178.                 String[] arr = nums.split("\\s+");
  179.                 for(String el : arr)
  180.                     tree.add(Double.parseDouble(el));
  181.                 notCorrect = false;
  182.             } catch (Exception err) {
  183.                 System.out.println("Произошла ошибка при открытии файла, убедитесь, что файл существует, либо проверьте правильность введенных данных. В файле должны содержаться вещественные числа, введенные в одну строку и разделенные одиночным пробелом");
  184.             }
  185.         }
  186.         return tree;
  187.     }
  188.  
  189.     static BinaryTree inputTree(Scanner scan) {
  190.         String choice = "";
  191.         boolean notCorrect = true;
  192.         System.out.println("Введите [c], если хотите ввести данные из консоли, либо [f], если хотите ввести данные из файла");
  193.         while(notCorrect) {
  194.             choice = scan.nextLine();
  195.             if(choice.equals("f") || choice.equals("c"))
  196.                 notCorrect = false;
  197.             else
  198.                 System.out.println("Введите либо [c], либо [f]");
  199.         }
  200.  
  201.         if(choice.equals("c"))
  202.             return inputTreeFromConsole(scan);
  203.         return inputTreeFromFile(scan);
  204.     }
  205.  
  206.     static void showMaxPath(ArrayList<Node> path) {
  207.         for(Node node : path)
  208.             System.out.print(node.value + " ");
  209.         System.out.println("");
  210.     }
  211.  
  212.     static void deleteCentralVertex(BinaryTree tree) {
  213.         if(tree.root != null) {
  214.             ArrayList<Node> maxPath = tree.maxPath();
  215.             System.out.println("Максимальный путь:");
  216.             showMaxPath(maxPath);
  217.             boolean isCentralVertexExists = maxPath.size() > 1 && maxPath.size() % 2 != 0;
  218.             if(isCentralVertexExists) {
  219.                 Node centralVertex = maxPath.get(maxPath.size() / 2);
  220.                 double vertexValue = centralVertex.value;
  221.                 tree.removeVertex(centralVertex);
  222.                 System.out.println("Дерево после удаления центральной вершины " + vertexValue + ":");
  223.                 System.out.println(tree.takeVisual());
  224.             } else {
  225.                 System.out.println("Максимальный путь данного дерева не содержит центральную вершину");
  226.             }
  227.         }
  228.     }
  229.  
  230.     static void saveResult(String treeStr, Scanner scan) {
  231.         System.out.println("Хотите сохранить результат в файл? [д/н]");
  232.         boolean notCorrect = true;
  233.         String choice = "";
  234.         while(notCorrect) {
  235.             choice = scan.nextLine();
  236.             if(choice.equals("д") || choice.equals("н"))
  237.                 notCorrect = false;
  238.             else
  239.                 System.out.println("Введите либо [д], либо [н]");
  240.         }
  241.  
  242.         if(choice.equals("д")) {
  243.             System.out.println("Введите имя файла");
  244.             String fileName = scan.nextLine() + ".txt";
  245.             try(FileWriter fw = new FileWriter(fileName)) {
  246.                 fw.write(treeStr);
  247.                 System.out.println("Результат успешно сохранен в файл " + fileName);
  248.             } catch (IOException err) {
  249.                 System.out.println("Возникла ошибка при записи результата в файл");
  250.             }
  251.         }
  252.     }
  253.  
  254.     public static void main(String[] args) {
  255.         System.out.println("Данная программа позволяет создать дерево двоичного поиска, найти максимальный путь между вершинами и удалить центральную вершину этого пути");
  256.         Scanner scan = new Scanner(System.in);
  257.         BinaryTree tree = inputTree(scan);
  258.         System.out.println("Введенное дерево:");
  259.         System.out.println(tree.takeVisual());
  260.         deleteCentralVertex(tree);
  261.         saveResult(tree.takeVisual(), scan);
  262.     }
  263. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement