Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.ArrayList;
- import java.util.Objects;
- import java.util.Scanner;
- public class Main {
- static Scanner scanner = new Scanner(System.in);
- public static boolean exit = false;
- public static Tree tree = new Tree();
- public static ArrayList<Integer> keys = new ArrayList<>();
- public static void main (String[] args) throws IOException{
- System.out.println("The program demonstrate tree as a data structure.");
- while (!exit) {
- showInfo();
- chooseAction();
- }
- }
- public static void showInfo () {
- System.out.println("1 - build an empty tree");
- System.out.println("2 - add a new item in the tree");
- System.out.println("3 - remove an item from the tree");
- System.out.println("4 - show tree");
- System.out.println("5 - open tree from file");
- System.out.println("6 - save tree in file");
- System.out.println("7 - exit");
- }
- private static int inputData() {
- int n = 0;
- boolean isIncorrect;
- final int MIN_SIZE = 1;
- do {
- isIncorrect = false;
- try {
- n = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please enter an integer number");
- }
- if (n < MIN_SIZE && !isIncorrect) {
- System.out.println("Please enter a positive number");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return n;
- }
- private static int inputKey() {
- int n = 0;
- boolean isIncorrect;
- do {
- isIncorrect = false;
- try {
- n = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please enter an integer number");
- }
- } while (isIncorrect);
- return n;
- }
- public static void chooseAction () throws IOException {
- int chose;
- boolean isIncorrect;
- final int MAX = 8;
- System.out.println("Please, choose:");
- do {
- chose = inputData();
- isIncorrect = false;
- if ((chose > MAX) || (chose < 1)) {
- isIncorrect = true;
- System.out.println("Please enter the correct function number.");
- }
- } while (isIncorrect);
- switch (chose) {
- case 1 -> buildTree();
- case 2 -> addNode();
- case 3 -> removeNode();
- case 4 -> showTree();
- case 5 -> openFile();
- case 6 -> saveData();
- case 7 -> exit = true;
- }
- }
- public static void buildTree () {
- tree.createTree();
- System.out.println("Ready!");
- System.out.println(); // просто пустая строка для удобства чтения
- }
- public static boolean checkExistenceOrUniqueness (int nodeToDelete) {
- for (Integer key : keys) {
- if (nodeToDelete == key) {
- return true;
- }
- }
- return false;
- }
- public static boolean checkUniqueness (int[] keysFromFile) {
- for (int i = 0; i < keysFromFile.length; i++){
- for (int j = i + 1; j < keysFromFile.length; j++){
- if (keysFromFile[i] == keysFromFile[j]) {
- System.out.println("There is(are) repetition(s) in your file. Change raw data.");
- return false;
- }
- }
- }
- for (int i = 0; i < keysFromFile.length; i++) {
- if (keys.contains(keysFromFile[i])) {
- System.out.println("Element(s) which is(are) tried to be added already exist(s). Change raw data.");
- return false;
- }
- }
- return true;
- }
- public static void addNode () {
- System.out.println("Input node:");
- int node = inputKey();
- if (checkExistenceOrUniqueness(node)) {
- System.out.println("Unfortunately it is impossible to add node which already exists. Enter again.");
- } else {
- tree.addNode(node);
- keys.add(node);
- System.out.println("Node \"" + node +"\" added.");
- }
- System.out.println(); // просто пустая строка для удобства чтения
- }
- public static void removeNode () {
- System.out.println("Input an item for deleting.");
- int nodeToDelete = inputKey();
- int index;
- if (tree.getRoot() != null) {
- if (checkExistenceOrUniqueness(nodeToDelete)) {
- tree.deleteNode(nodeToDelete);
- index = keys.indexOf(nodeToDelete);
- keys.remove(index);
- System.out.println("Ready!");
- } else
- System.out.println("There is no such node.");
- } else {
- System.out.println("Tree is empty.");
- }
- System.out.println(); // просто пустая строка для удобства чтения
- }
- public static void showTree () {
- if (tree.getRoot() != null) {
- System.out.println("For better user experience turn your monitor clockwise)");
- Tree root = tree.getRoot();
- tree.printTree(root, 0);
- } else {
- System.out.println("Tree is empty.");
- }
- System.out.println(); // просто пустая строка для удобства чтения
- }
- public static String inputFilePath() {
- String path;
- boolean isIncorrect;
- do {
- isIncorrect = false;
- System.out.println("Input file path:");
- path = scanner.nextLine();
- File file = new File(path);
- if (!file.exists()) {
- System.out.println("Wrong way to file.");
- isIncorrect = true;
- }
- if (!file.canRead() && file.exists()) {
- System.out.println("Impossible to read a file.");
- isIncorrect = true;
- }
- if (!file.canWrite() && file.canRead()) {
- System.out.println("Impossible to write a file.");
- isIncorrect = true;
- }
- } while (isIncorrect);
- return path;
- }
- public static String[] deleteSpacesInArray (String[] keys) {
- int counterOfSpaces = 0;
- for (int j = 0; j < keys.length; j++) {
- if (!Objects.equals(keys[j], "")) {
- counterOfSpaces++;
- }
- }
- int i = 0;
- String[] newArr = new String[counterOfSpaces];
- for (int j = 0; j < keys.length; j++) {
- if (!Objects.equals(keys[j], "")) {
- newArr[i] = keys[j];
- i++;
- }
- }
- return newArr;
- }
- public static boolean checkArrayOfStrings (String[] keys) {
- for (int j = 0; j < keys.length; j++){
- try {
- Integer.parseInt(keys[j]);
- } catch (Exception e) {
- System.out.println("Check file, it shouldn't contains smth except numbers.");
- return false;
- }
- }
- return true;
- }
- public static int[] getArrOfKeys (String[] keys) {
- int[] keysFromFile = new int[keys.length];
- for (int j = 0; j < keys.length; j++) {
- keysFromFile[j] = Integer.parseInt(keys[j]);
- }
- return keysFromFile;
- }
- public static void openFile () {
- System.out.println("Example of string with tree's nodes:");
- System.out.println("node1 - node2 - node3 - ... - nodeN");
- System.out.println("P.S. after every position expected only space. Nodes from file will be added to existed tree.");
- String path = inputFilePath();
- String str;
- String[] mas;
- try {
- Scanner fileReader = new Scanner(new File(path));
- str = fileReader.nextLine();
- mas = str.split(" ");
- mas = deleteSpacesInArray(mas);
- if (checkArrayOfStrings(mas)) {
- int[] keysFromFile = getArrOfKeys(mas);
- if (checkUniqueness(keysFromFile)) {
- for (int j = 0; j < keysFromFile.length; j++) {
- tree.addNode(keysFromFile[j]);
- keys.add(keysFromFile[j]);
- }
- System.out.println("Ready!");
- }
- }
- } catch (Exception q) {
- System.out.println("Something went wrong, check file.");
- }
- }
- public static void saveData () throws IOException {
- if (tree.getRoot() != null) {
- String path = inputFilePath();
- FileWriter writer = new FileWriter(path);
- String result = "";
- for (Integer key: keys) {
- result = result + Integer.toString(key) + " ";
- }
- writer.write(result);
- writer.close();
- System.out.println("Ready!");
- } else {
- System.out.println("Tree is empty, add some nodes!");
- }
- }
- }
- ======================================================class2======================================================
- public class Tree {
- private int key;
- private Tree leftChild;
- private Tree rightChild;
- public static Tree rootNode;
- public Tree getRoot() {
- return rootNode;
- }
- public int getKey() {
- return this.key;
- }
- public void setKey(final int key) {
- this.key = key;
- }
- public Tree getLeftChild() {
- return this.leftChild;
- }
- public void setLeftChild(final Tree leftChild) {
- this.leftChild = leftChild;
- }
- public Tree getRightChild() {
- return this.rightChild;
- }
- public void setRightChild(final Tree rightChild) {
- this.rightChild = rightChild;
- }
- public void createTree() {
- rootNode = null;
- }
- public void addNode(int key) {
- Tree newNode = new Tree();
- newNode.setKey(key);
- if (rootNode == null) {
- rootNode = newNode;
- } else {
- Tree currentNode = rootNode;
- Tree parentNode;
- while (true) {
- parentNode = currentNode;
- if (key == currentNode.getKey()) {
- return;
- } else if (key < currentNode.getKey()) {
- currentNode = currentNode.getLeftChild();
- if (currentNode == null) {
- parentNode.setLeftChild(newNode);
- return;
- }
- } else {
- currentNode = currentNode.getRightChild();
- if (currentNode == null) {
- parentNode.setRightChild(newNode);
- return;
- }
- }
- }
- }
- }
- public void deleteNode(int value) {
- Tree currentNode = rootNode;
- Tree parentNode = rootNode;
- boolean isLeftChild = true;
- while (currentNode.getKey() != value) {
- parentNode = currentNode;
- if (value < currentNode.getKey()) {
- isLeftChild = true;
- currentNode = currentNode.getLeftChild();
- }
- else {
- isLeftChild = false;
- currentNode = currentNode.getRightChild();
- }
- }
- if (currentNode.getLeftChild() == null && currentNode.getRightChild() == null) {
- if (currentNode == rootNode)
- rootNode = null;
- else if (isLeftChild)
- parentNode.setLeftChild(null);
- else
- parentNode.setRightChild(null);
- }
- else if (currentNode.getRightChild() == null) {
- if (currentNode == rootNode)
- rootNode = currentNode.getLeftChild();
- else if (isLeftChild)
- parentNode.setLeftChild(currentNode.getLeftChild());
- else
- parentNode.setRightChild(currentNode.getLeftChild());
- }
- else if (currentNode.getLeftChild() == null) {
- if (currentNode == rootNode)
- rootNode = currentNode.getRightChild();
- else if (isLeftChild)
- parentNode.setLeftChild(currentNode.getRightChild());
- else
- parentNode.setRightChild(currentNode.getRightChild());
- }
- else {
- Tree successor = getSuccessor(currentNode);
- if (currentNode == rootNode)
- rootNode = successor;
- else if (isLeftChild)
- parentNode.setLeftChild(successor);
- else
- parentNode.setRightChild(successor);
- }
- }
- private Tree getSuccessor(Tree deleteNode) {
- Tree successorParent = deleteNode;
- Tree successor = deleteNode;
- Tree current = deleteNode.getRightChild();
- while (current != null) {
- successorParent = successor;
- successor = current;
- current = current.getLeftChild();
- }
- if (successor != deleteNode.getRightChild()) {
- successorParent.setLeftChild(successor.getRightChild());
- successor.setRightChild(deleteNode.getRightChild());
- }
- successor.setLeftChild(deleteNode.getLeftChild());
- return successor;
- }
- public void printTree(Tree node, int level) {
- if (node == null) {
- return;
- }
- printTree(node.getRightChild(), level + 1);
- for (int i = 0; i < level; i++) {
- System.out.print(" ");
- }
- System.out.println(node.getKey());
- printTree(node.getLeftChild(), level + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement