1 year ago
#379854
checheche
What cause the error "unchecked or unsafe operations " for my tree implementation
It works fine on my IDE, but why I am getting "unchecked or unsafe operations" when I compile. I think I have to do something with the generic types but I cannot catch that.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BetterBST<T extends Comparable<? super T>> extends BinarySearchTree<T>{
public BetterBST(){
root = null;
}
public BetterBST(BinaryNode<T> root){
this.root = root;
}
public void printSpace(double x){
while (x>0){
System.out.print(" ");
x--;
}
}
public int height(){
if( root == null )
return -1;
else
return 1 + Math.max( depth( root.left ), depth( root.right ) );
}
public int depth(BinaryNode<T> t) {
if( t == null )
return -1;
else
return 1 + Math.max( depth( t.left ), depth( t.right ) );
}
before I make " unchecked or unsafe operations" warning, the compiler pointed out this method "public T imbalance()" to be changed but I did not know how to and somehow the error has changed to unchecked or unsafe operations.
public T imbalance() {
if( root == null ){
return null;
}
return imbalance(root);
}
private T imbalance(BinaryNode<T> t) {
int rHeight, lHeight;
T ret = null;
if (t.left == null){
lHeight = -1;
}
else{
lHeight = depth(t.left);
}
if(t.right == null){
rHeight = -1;
}
else{
rHeight = depth(t.right);
}
if (java.lang.Math.abs(rHeight - lHeight) > 1) {
ret = t.data;
}
else {
if (t.left != null) {
ret= imbalance(t.left);
}
if (t.right != null) {
ret = imbalance(t.right);
}
}
return ret;
}
private BinaryNode<T> currSmallest; // the current smallest node greater than
private T smallestGreaterThan(T x, BinaryNode<T> t, boolean notFoundGreater){
if( root == null ){
return null;
}
int compareResult = x.compareTo(t.data);
if (x.compareTo(findMax()) > 0 || x.compareTo(findMax()) == 0){
return null;
}
if (compareResult > 0 || compareResult == 0){
if (t.right != null) {
smallestGreaterThan(x, t.right, true);
}
}
else if (compareResult < 0) {
if (notFoundGreater){
currSmallest = t;
}
if (t.data.compareTo(currSmallest.data) < 0) {
currSmallest = t;
}
if (t.left != null) {
smallestGreaterThan(x, t.left, false);
}
}
return currSmallest.data;
}
}
public LinkedList<BinaryNode<T>> levelOrderTraversal(BinaryNode<T> root){
Queue<BinaryNode<T>> queue = new LinkedList();
queue.add(root);
LinkedList<BinaryNode<T>> result = new LinkedList<>();
while (!queue.isEmpty()) {
BinaryNode<T> current = queue.poll();
result.add(current);
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
return result;
}
}
java
compiler-errors
tree
syntax-error
0 Answers
Your Answer