Advertisement
MrGhost75

LAB2_TREE

May 19th, 2020
1,074
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.58 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.ArrayList;
  3.  
  4. /*
  5. Задано дерево в виде таблицы.
  6. В первой колонке номер узла – целое число, вторая колоночка таблицы – родитель.
  7. Задачи:
  8. (1)Для произвольного узла вывести часть дерева, которая связывает его с корнем дерева.
  9. (2)Вывести дочернее поддерево.
  10. (3)Выбираем два произвольных узла и строим часть дерева, которая их соединяет.
  11. */
  12.  
  13. public class Tree {
  14.  
  15.     public static void main(String[] args) throws IOException {
  16.  
  17.         BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
  18.  
  19.         //Создадим произвольное дерево в виде таблицы.
  20.         Integer[][] tree = {
  21.                 {8, null},
  22.                 {4, 8},
  23.                 {9, 8},
  24.                 {10, 9},
  25.                 {11, 10},
  26.                 {7, 10},
  27.                 {2, 4},
  28.                 {6, 4},
  29.                 {1, 2},
  30.                 {3, 2}
  31.         };
  32.  
  33.         //Выведем его на экран.
  34.         System.out.println("Ваше дерево в виде таблицы:");
  35.         for (int i = 0; i < tree.length; i++) {
  36.             for (int j = 0; j < tree[i].length; j++) {
  37.                 System.out.print(tree[i][j] + "\t");
  38.             }
  39.             System.out.println();
  40.         }
  41.  
  42.         //(1)Вывод пути от произвольного узла до корня дерева.
  43.         ArrayList<Integer> path = new ArrayList<>();
  44.  
  45.         System.out.print("\nВведите число(узел, путь до которого вы хотите найти): ");
  46.         int treeNode = Integer.parseInt(consoleReader.readLine());
  47.         System.out.println("Путь от узла со значением " + treeNode + " до корня дерева:");
  48.  
  49.         pathToTheRoot(treeNode, tree, path);
  50.         printArrayList(path);
  51.         System.out.println();
  52.  
  53.         //(2)Вывод дочернего поддерева.
  54.         System.out.print("\nВведите число(узел, поддерево которого вы хотите получить): ");
  55.         treeNode = Integer.parseInt(consoleReader.readLine());
  56.         System.out.println("Поддерево узла со значением " + treeNode + ":");
  57.  
  58.         childTree(treeNode, tree);
  59.         System.out.println();
  60.  
  61.  
  62.         //(3)Выбираем два произвольных узла и строим часть дерева, которая их соединяет.
  63.         System.out.print("\nВведите два произвольных числа(узлы): ");
  64.         String[] nodes = consoleReader.readLine().split("\\s+");
  65.  
  66.         int firstTreeNode = Integer.parseInt(nodes[0]);
  67.         ArrayList<Integer> firstPath = new ArrayList<>();
  68.         pathToTheRoot(firstTreeNode, tree, firstPath);
  69.  
  70.         int secondTreeNode = Integer.parseInt(nodes[1]);
  71.         ArrayList<Integer> secondPath = new ArrayList<>();
  72.         pathToTheRoot(secondTreeNode, tree, secondPath);
  73.  
  74.         connectionOfTwoNodes(firstPath, secondPath);
  75.  
  76.         consoleReader.close();
  77.     }
  78.  
  79.     //Функция для 1-го задания.
  80.     public static void pathToTheRoot(Integer treeNode, Integer[][] tree, ArrayList<Integer> path) {
  81.         for (int i = 0; i < tree.length; i++) {
  82.             if (tree[i][0] == treeNode) {
  83.                 if (tree[i][1] == null) {
  84.                     path.add(treeNode);
  85.                     break;
  86.                 }
  87.                 else {
  88.                     path.add(treeNode);
  89.                     Integer parent = tree[i][1];
  90.                     pathToTheRoot(parent, tree, path);
  91.                 }
  92.             }
  93.         }
  94.     }
  95.  
  96.     //Функция для 2-го задания
  97.     public static void childTree(Integer treeNode, Integer[][] tree) {
  98.         for (int i = 0; i < tree.length; i++) {
  99.             if(tree[i][1] == treeNode) {
  100.                 int child = tree[i][0];
  101.                 System.out.print(treeNode + " -> " + child + "\n");
  102.                 childTree(child, tree);
  103.             }
  104.         }
  105.     }
  106.  
  107.     //Функция для 3-го задания
  108.     public static void connectionOfTwoNodes(ArrayList<Integer> firstPath, ArrayList<Integer> secondPath) {
  109.         int firstPathIndex = 0;
  110.         int secondPathIndex = 0;
  111.         for (int i = 0; i < firstPath.size(); i++) {
  112.             for (int j = 0; j < secondPath.size(); j++) {
  113.                 if (firstPath.get(i) == secondPath.get(j)) {
  114.                     firstPathIndex = i;
  115.                     secondPathIndex = j;
  116.                     break;
  117.                 }
  118.             }
  119.             if (firstPathIndex != 0 || secondPathIndex != 0) break;
  120.         }
  121.         for (int i = 0; i <= firstPathIndex; i++) {
  122.             if(i == firstPathIndex) System.out.print(firstPath.get(i));
  123.             else System.out.print(firstPath.get(i) + " <- ");
  124.         }
  125.         for (int i = secondPathIndex - 1; i >= 0; i--) {
  126.             System.out.print(" -> " + secondPath.get(i));
  127.         }
  128.     }
  129.  
  130.     //Вывод ArrayList'а на экран в красивом виде
  131.     public static void printArrayList(ArrayList<Integer> list) {
  132.         for(int i = 0; i < list.size(); i++) {
  133.             if (i == list.size() - 1) System.out.print(list.get(i));
  134.             else System.out.print(list.get(i) + " <- ");
  135.         }
  136.         System.out.println();
  137.     }
  138.  
  139. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement