Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package assignment2;
  2.  
  3. import java.io.File;
  4. import java.util.Scanner;
  5.  
  6. public class BinarySearchTree extends LinkedBinaryTree {
  7.     Scanner reader;
  8.     LinkedBinaryTree tree = new LinkedBinaryTree();
  9.    
  10.     /*
  11.      * readIn performs the following operations:
  12.      * (1) reads from fileName word by word
  13.      * (2) for every new word found in fileName a new BTNode is created
  14.      * and added to T according to the rules of BST insertion
  15.      * (3) for every duplicate word, wordCounter for the corresponding BTNode is incremented
  16.      */
  17.     public void readIn(String fileName) {
  18.        
  19.         BTNode current = root;
  20.         BTNode prev = null;
  21.        
  22.         try {
  23.             reader = new Scanner(new File(fileName));
  24.         } catch (Exception e) {
  25.             System.out.println("Could not find file!");
  26.         }
  27.  
  28.         while (reader.hasNext()) {
  29.             String word = reader.next();
  30.            
  31.             while (current != null) { // pointer for inserting new node
  32.                 prev = current;
  33.  
  34.                 if (current.element().compareTo(word) < 0) {
  35.                     current = current.right;
  36.                 } else {
  37.                     current = current.left;
  38.                 }
  39.             }
  40.  
  41.             if (root == null) { // if tree is empty
  42.                 tree.addRoot(word);
  43.             } else if (prev.element().compareTo(word) < 0) {
  44.                 tree.addRight(prev, word);
  45.             } else {
  46.                 tree.addLeft(prev, word);
  47.             }
  48.  
  49.         }
  50.     }
  51.  
  52.     /*
  53.      * maxSearchPath finds and returns the length of the longest search path in T
  54.      */
  55.     public int maxSearchPath() {
  56.         return treeHeight(tree.root);
  57.     }
  58.  
  59.     /*
  60.      * printWordsSorted prints all distinct words found in fileName, in sorted order
  61.      */
  62.     public void printWordsSorted() {
  63.     }
  64.  
  65.     /*
  66.      * printTenMostCommonWords finds and prints ten most common words from
  67.      * fileName together with their respective wordCounter -s
  68.      */
  69.     public void printTenMostCommonWords() {
  70.     }
  71.    
  72.     public int treeHeight(BTNode node) {
  73.         if(node == null) {
  74.             return -1;
  75.         }
  76.         return 1 + Math.max(treeHeight(node.left), treeHeight(node.right));
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement