Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Binärbaum<T extends Comparable<T>> {
- Knoten<T> root;
- Knoten<T> wurzelGerade;
- public void add(T content) {
- if (root == null) {
- root = new Knoten<T>(content);
- wurzelGerade = root;
- }
- // Linker Teilbaum
- else if (content.compareTo(wurzelGerade.content) < 0) {
- if (wurzelGerade.links == null) {
- wurzelGerade.links = new Knoten<T>(content);
- wurzelGerade = root;
- } else {
- wurzelGerade = wurzelGerade.links;
- add(content);
- }
- }
- // Rechter Teilbaum
- else if (content.compareTo(wurzelGerade.content) > 0) {
- if (wurzelGerade.rechts == null) {
- wurzelGerade.rechts = new Knoten<T>(content);
- wurzelGerade = root;
- } else {
- wurzelGerade = wurzelGerade.rechts;
- add(content);
- }
- }
- }
- public void ausgeben() {
- int ebene = 0;
- ausgeben(root, ebene, " Wurzel", 0);
- }
- public void ausgeben(Knoten<T> temp, int ebene, String linksRechts, int seite) {
- ebene++;
- if(seite == 1) linksRechts = linksRechts + " Links ";
- if(seite == 2) linksRechts = linksRechts + " Rechts ";
- if (temp.links != null) {
- ausgeben(temp.links, ebene, linksRechts, 1);
- }
- if (temp.rechts != null) {
- ausgeben(temp.rechts, ebene, linksRechts, 2);
- }
- System.out.println("Ebene " +(ebene-1) +": " +temp + linksRechts);
- }
- public static class Knoten<E> {
- Knoten<E> links;
- Knoten<E> rechts;
- E content;
- public Knoten(E content) {
- this.content = content;
- }
- public String toString() {
- return String.valueOf(content);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement