Advertisement
heavenriver

2011_05_06.java (ex. 2)

Jan 1st, 2013
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. // Esame del 6 maggio 2011, esercizio 2
  2. // Ricordarsi di specificare sempre, nei commenti al codice, l'utilità di ogni metodo.
  3.  
  4. class BSTNode
  5.     {
  6.     int key;
  7.     E elem;
  8.     BSTNode left;
  9.     BSTNode right;
  10.     public BSTNode(int key, E elem);
  11.     public int getKey();
  12.     public E getElem();
  13.     public BSTNode left();
  14.     public BSTNode right();
  15.     public boolean hasLeft();
  16.     public boolean hasRight();
  17.     }
  18.  
  19. class BST
  20.     {
  21.     private BSTNode root;
  22.     public BST(int rootKey, E rootElem);
  23.     public BSTNode insert(int key, E elem);
  24.     public BSTNode remove(int key);
  25.     public BSTNode removeMin(BSTNode start); // Rimuove il nodo minimo del sottoalbero a radice start
  26.     public BSTNode find(int key);
  27.     public Collection<BSTNode> findAll(int key);
  28.    
  29.     public List<Integer> chiaviOrdinate() // Costo computazionale Theta(n) per definizione; attraversamento inorder
  30.         {
  31.         List<Integer> out = new LinkedList<Integer>();
  32.         trovaChiavi(root, out);
  33.         return out;
  34.         }
  35.     public void trovaChiavi(BSTNode n, List<Integer> l)
  36.         {
  37.         if(n.hasLeft()) trovaChiavi(n.left, out);
  38.         out.add(n.getKey());
  39.         if(n.hasRight()) trovaChiavi(n.right, out);
  40.         }
  41.    
  42.     public boolean verificaBilanciamento() // Costo computazionale non richiesto
  43.         {
  44.         int i = 0;
  45.         isBilanciato(root, i);
  46.         return Math.abs(i) <= 1;
  47.         }
  48.     public int isBilanciato(BSTNode n, int bal)
  49.         {
  50.         if(!n.hasLeft() && !n.hasRight()) return 0;
  51.         if(n.hasLeft() && n.hasRight())
  52.             {
  53.             bailLeft = Math.abs(isBilanciato(n.left, i);
  54.             bailRight = Math.abs(isBilanciato(n.right, i);
  55.             if(Math.abs(bailLeft) <= 1 && Math.abs(bailRight) <= 1)
  56.                 return bailLeft - bailRight;
  57.             }
  58.         if(n.hasLeft() && !n.hasRight()) return isBilanciato(n.left, bal + 1);
  59.         else return isBilanciato(n.right, bal - 1);
  60.         }
  61.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement