89 lines
2.3 KiB
Java
89 lines
2.3 KiB
Java
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.PriorityQueue;
|
|
import java.util.Comparator;
|
|
|
|
public class Node
|
|
{
|
|
private Node left;
|
|
private Node right;
|
|
private int anzahl;
|
|
private Character buchstabe;
|
|
|
|
public Node()
|
|
{
|
|
}
|
|
|
|
public Node(Node left, Node right) //constructor für node
|
|
{
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
|
|
|
|
//set und get methoden für verschiedenes
|
|
public Node getLeft(){return left;}
|
|
|
|
public void setLeft(Node left){this.left = left;}
|
|
|
|
public Node getRight(){return right;}
|
|
|
|
public void setRight(Node right){this.right = right;}
|
|
|
|
public int getAnzahl(){return anzahl;}
|
|
|
|
public void setAnzahl(int anzahl){this.anzahl = anzahl;}
|
|
|
|
public Character getBuchstabe(){return buchstabe;}
|
|
|
|
public void setBuchstabe(Character buchstabe){this.buchstabe = buchstabe;}
|
|
|
|
public static Node erstellen(Map<Character, Integer> häufigkeiten)
|
|
{
|
|
//erstellt PriorityQueue die nach Anzahl sortiert
|
|
PriorityQueue<Node> nodes = new PriorityQueue<Node>(Comparator.comparingInt(n -> n.anzahl));
|
|
|
|
for (var entry : häufigkeiten.entrySet()) //erstellt die Nodes und brfüllt die queue damit
|
|
{
|
|
Node node = new Node();
|
|
node.setAnzahl(entry.getValue());
|
|
node.setBuchstabe(entry.getKey());
|
|
nodes.add(node);
|
|
}
|
|
|
|
|
|
|
|
while (nodes.size() > 1) //erstellt den Baum
|
|
{
|
|
Node min1 = nodes.poll();
|
|
Node min2 = nodes.poll();
|
|
Node wurzel = new Node();
|
|
wurzel.setLeft(min1);
|
|
wurzel.setRight(min2);
|
|
wurzel.setAnzahl(min1.getAnzahl() + min2.getAnzahl());
|
|
nodes.add(wurzel);
|
|
}
|
|
return nodes.poll();
|
|
}
|
|
|
|
public void add(Node node) //fügt ein Kind an die freie Stelle von dem baum hin wenn möglich
|
|
{
|
|
if(left == null) //als erstes überprüft es die linke Seite
|
|
{
|
|
left= node;
|
|
return;
|
|
}
|
|
|
|
if(right == null) //danach überprüft es die linke Seite
|
|
{
|
|
right= node;
|
|
return;
|
|
}
|
|
}
|
|
|
|
public boolean hatPlatzKinder() //überprüft ob der baum schon "voll" ist
|
|
{
|
|
return left==null || right==null;
|
|
}
|
|
}
|