APL/DEV 3.2/TP08/Tri/TreeNode.java
2023-03-07 16:14:57 +01:00

79 lines
2.3 KiB
Java

public class TreeNode<T> {
private T value;
private TreeNode<T> lesser;
private TreeNode<T> greater;
private SearchTree<T> parentTree;
public TreeNode(SearchTree<T> parentTree, T object) {
this.parentTree = parentTree;
this.value = object;
}
public void add(T object) {
switch (parentTree.getComparator().compare(value, object)) {
case -1:
if (lesser != null) lesser.add(object);
else lesser = new TreeNode<T>(parentTree, object);
break;
case 0:
throw new IllegalArgumentException("Value already in tree");
case 1:
if (greater != null) greater.add(object);
else greater = new TreeNode<T>(parentTree, object);
break;
}
}
public void remove(T object) {
if (lesser.getValue().equals(object)) {
T a = lesser.getLesser().getValue();
T b = lesser.getGreater().getValue();
parentTree.add(a);
parentTree.add(b);
lesser = null;
} else if (greater.getValue().equals(object)) {
T a = greater.getLesser().getValue();
T b = greater.getGreater().getValue();
parentTree.add(a);
parentTree.add(b);
greater = null;
} else {
switch (parentTree.getComparator().compare(value, object)) {
case -1:
if (lesser != null) lesser.remove(object);
else return;
break;
case 0:
throw new IllegalStateException("Something fucked up");
case 1:
if (greater != null) greater.remove(object);
else return;
break;
}
}
}
public T getValue() {
return value;
}
public TreeNode<T> getLesser() {
return lesser;
}
public TreeNode<T> getGreater() {
return greater;
}
@Override
public String toString() {
String str = "";
if (greater != null) str += greater.toString();
str += value.toString() + " ";
if (lesser != null) str += lesser.toString() + " ";
return str;
}
}