Реализация дерева AVL (Java) - PullRequest
       119

Реализация дерева AVL (Java)

0 голосов
/ 26 апреля 2020

Мне дали задание реализовать дерево AVL для хранения словаря английского языка sh

Кажется, что дерево никогда не вставляет ни одного слова из файла, поэтому высота остается равной 0. Я скопировал части кода откуда-то еще и пытались заставить его работать, но я застрял в этой проблеме.

Все это компилируется, но я думаю, что мой метод вставки - проблемный c. Вот описание задания, которое мне было дано:

Импортировать слова из словаря из файла 29765-8.txt (находится здесь https://drive.google.com/file/d/17zi9bHOi4YrhvPzFFhFLekEcB8LEh_5E/view) и вставлять их в дерево AVL. Во время этого процесса вывод не выводится.

После завершения вставки программа должна распечатать одно число, показывающее высоту конечного дерева AVL. В следующей строке программа должна вывести одно приглашение с пробелом после ($) и ждать, пока пользователь введет команду. После ввода правильной команды программа должна выполнить соответствующую задачу, а затем снова распечатать приглашение (с пробелом), если только команда не должна выйти. Если бы кто-то мог объяснить мне, как это исправить, я был бы очень признателен.

Вот что у меня есть:

import java.util.*;

import java.io.*;

// class to represent AVL node
class Dictionary{
// variable to store the string word
   String word;

   // store height
   int h;

   Dictionary leftChild, rightChild;
   // vector to meaning
   Vector v;
   // constructor of Dictionary
   Dictionary(String data,String meaning){
      word = data;
      v = new Vector();
      v.add(meaning);
      h = 1;
   }
}

class AVLTree
{

   // Root node
   Dictionary Root;

   static int flag = 0;
   // function for getting height
   int getHeight(Dictionary n){
      if (n == null)
         return 0;
      return n.h;
   }
   // function to get maximum
   int getMax(int x, int y){
      return (x>y)?x:y;
   }
   // rotate Right for balancing
   Dictionary rotateRight(Dictionary input){
      Dictionary temp1 = input.leftChild;
      Dictionary temp2 = temp1.rightChild;
      // rotate
      temp1.rightChild = input;
      input.leftChild = temp2;
      // update h
      input.h = getMax(getHeight(input.leftChild), getHeight(input.rightChild)) + 1;
      temp1.h = getMax(getHeight(temp1.leftChild), getHeight(temp1.rightChild)) + 1;
      //return root
      return temp1;
   }
   // rotate left for balancing
   Dictionary leftRotate(Dictionary input){
      Dictionary temp1 = input.rightChild;
      Dictionary temp2 = temp1.leftChild;
      // rotate
      temp1.leftChild = input;
      input.rightChild = temp2;
      // update h
      input.h = getMax(getHeight(input.leftChild), getHeight(input.rightChild)) + 1;
      temp1.h = getMax(getHeight(temp1.leftChild), getHeight(temp1.rightChild)) + 1;
      // return root
      return temp1;
   }
   // get factor of balance
   int balanceFactor(Dictionary n){
      if(n == null)
         return 0;
      return getHeight(n.leftChild) - getHeight(n.rightChild);
   }
   Dictionary insert(Dictionary root, String word, String meaning){
      // insert according to bst
      if(root == null)
         return (new Dictionary(word,meaning));
      if((word.compareTo(root.word)) < 0)
         root.leftChild = insert(root.leftChild, word,meaning);
      else if ((word.compareTo(root.word)) > 0)
         root.rightChild = insert(root.rightChild, word,meaning);

  // if allready present insert meaning
  else{
     (root.v).add(meaning);
     return root;
  }
  // update height
  root.h = 1 + getMax(getHeight(root.leftChild),getHeight(root.rightChild));
  // get balance factor
  int balFactor = balanceFactor(root);
  // if unbalanced
  if (balFactor > 1 && (word.compareTo(root.leftChild.word)) < 0)
     return rotateRight(root);
  // case = right right
  if (balFactor < -1 && (word.compareTo(root.leftChild.word)) > 0)
     return leftRotate(root);
  // case = left right
  if (balFactor > 1 && (word.compareTo(root.leftChild.word)) > 0){
     root.leftChild = leftRotate(root.leftChild);
     return rotateRight(root);
  }
  // case = right left
  if (balFactor < -1 && (word.compareTo(root.leftChild.word)) < 0){
     root.rightChild = rotateRight(root.rightChild);
     return leftRotate(root);
  }
  // else no change
  return root;


}

  // search
   void search(Dictionary Root,String word) {
      if (Root != null) {
         if(word.equals(Root.word)){
            flag = 1;
            for(int i=0;i<Root.v.size();i++)
               System.out.println(Root.v.get(i));
         }
         this.search(Root.leftChild,word);
         this.search(Root.rightChild,word);
      }
   }

   public static void main(String[] args) throws FileNotFoundException
   {
      AVLTree tree = new AVLTree();

  // in input file word and its meaning is given in each line

  File input = new File("29765-8.txt");
  Scanner sc = new Scanner(input);
  Scanner scan = new Scanner(System.in);
  while (sc.hasNextLine()){
     String read = sc.nextLine();
     String arr[] = read.split(" ");
     String word = arr[0];
     String meaning = read.substring(arr[0].length()+1);
     tree.Root = tree.insert(tree.Root,word,meaning);
  }
  System.out.println(tree.getHeight(tree.Root));//Prints out 0 for height so far :(

  while(true){
     System.out.print(" ");
     String command = scan.next();
     if(command.equals("SEARCH")){
        String word = scan.next();
        flag = 0;
        tree.search(tree.Root,word);
        if(flag == 0)
           System.out.println("Word does not exist");
     }
     else if(command.equals("EXIT"))
        break;
     else
        System.out.println("Invalid Command");
  }
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...