This commit is contained in:
Emanuele Slusarz
2026-05-23 20:37:48 +02:00
parent 30b66dd99b
commit 66f053aba3
25 changed files with 1832 additions and 481 deletions
@@ -1,9 +1,11 @@
package binary_tree;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
@@ -517,4 +519,59 @@ public class LinkedBinaryTree<E> implements BinaryTree<E>{
}
}
/*
* TOTALE 2024-01-16
* Realizzare un metodo ricorsivo interno alla classe LinkedBinaryTree
* che dato l'albero binario corrente restituisca la distanza della foglia
* più vicina alla radice.
*/
public int shortestLeaf() {
if (root == null) throw new NullPointerException();
return shortestLeaf(root);
}
protected int shortestLeaf(BinaryNode<E> node) {
// Se questa è una foglia
if (node.getLeft() == null && node.getRight() == null) return 1;
// Recuperiamo l'altezza di sinistra e di destra
/*
* Nota BENE: Non si arriverà mai nella situazione in cui vi sono 2 MAX_VALUE assegnati al
* nodo corrente poichè il caso foglia è gestito sopra.
*/
int altezzaMinimaSinistra = (node.getLeft() != null) ? shortestLeaf(node.getLeft()) : Integer.MAX_VALUE;
int altezzaMinimaDestra = (node.getRight() != null) ? shortestLeaf(node.getRight()) : Integer.MAX_VALUE;
// Ritorno del valore foglia minimo
return Integer.min(altezzaMinimaSinistra, altezzaMinimaDestra) + 1;
}
/*
* TOTALE 2024-01-30
* Realizzare un metodo interno alla classe LinkedBinaryTree che dato l'albero binario
* corrente restituisca il numero di occorrenze di ciascun oggetto contenuto nei nodi dell'albero
*/
public Map<E, Integer> getElementsOccurrency() {
// Creazione Map
Map<E, Integer> mappa = new HashMap<E, Integer>();
if (root == null) return mappa;
getElementsOccurrency(root, mappa);
return mappa;
}
protected void getElementsOccurrency(BinaryNode<E> node, Map<E, Integer> mappa) {
// Se è un nodo nullo
if (node == null) return;
// Si proceda a sx e dx
if (node.getLeft() != null) getElementsOccurrency(node.getLeft(), mappa);
if (node.getRight() != null) getElementsOccurrency(node.getRight(), mappa);
// Si legge l'elemento corrente
E currentData = node.getData();
if (currentData == null) return;
if (mappa.get(currentData) == null) mappa.put(currentData, 1);
else mappa.put(currentData, 1 + mappa.get(currentData));
}
}