Noch fehlerhaftes Löschen im Baum.
parent
3d9fbcd8bb
commit
f8c0e96fdb
|
@ -20,6 +20,11 @@ public class Baum {
|
|||
wurzel.inorder();
|
||||
}
|
||||
|
||||
public void remove(int wert) {
|
||||
if (wurzel != null)
|
||||
wurzel.remove(wert);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
// Breitensuche
|
||||
if (wurzel == null)
|
||||
|
@ -86,6 +91,42 @@ public class Baum {
|
|||
ll.peek().breitensuche();
|
||||
}
|
||||
|
||||
public void remove(int wert) {
|
||||
if (wert < this.wert && links != null)
|
||||
if (links.wert == wert) {
|
||||
if (links.links == null && links.rechts == null) // keine Kinder
|
||||
links = null;
|
||||
else if (links.links != null && links.rechts == null) // linkes Kind
|
||||
links = links.links;
|
||||
else if (links.rechts != null && links.links == null) // rechtes Kind
|
||||
links = links.rechts;
|
||||
else {
|
||||
Knoten alt = links;
|
||||
links = links.links.größterImTeilbaum();
|
||||
links.links = alt.links;
|
||||
links.rechts = alt.rechts;
|
||||
}
|
||||
} else
|
||||
links.remove(wert);
|
||||
if (wert > this.wert && rechts != null)
|
||||
if (rechts.wert == wert)
|
||||
rechts = null;
|
||||
else
|
||||
rechts.remove(wert);
|
||||
}
|
||||
|
||||
private Knoten größterImTeilbaum() {
|
||||
if (this.rechts != null) {
|
||||
Knoten kind = this.rechts.größterImTeilbaum();
|
||||
if (rechts == kind)
|
||||
rechts = null;
|
||||
|
||||
return kind;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -7,10 +7,14 @@ public class Main {
|
|||
b1.add(42);
|
||||
b1.add(21);
|
||||
b1.add(84);
|
||||
b1.add(25);
|
||||
b1.add(27);
|
||||
|
||||
b1.add(11);
|
||||
|
||||
// b1.inorder();
|
||||
b1.remove(21);
|
||||
|
||||
b1.inorder();
|
||||
|
||||
System.out.println(b1.toString());
|
||||
|
||||
|
|
Loading…
Reference in New Issue