下面是我用来查找某个元素位置的代码。我使用二叉树来存储我的字典,我想知道为什么它会显示可比较类型的警告。我必须在我的项目中使用它,其中元素是字符串类型。
public int get(Comparable element){
return getPosition(element,root);
}
private int getPosition(Comparable element, TreeNode root){
int count = 0;
if (root == null){
return -1;
}else{
Stack t = new Stack();
t.push(root);
while(!t.empty()){
TreeNode n = (TreeNode)t.pop();
if(element.compareTo(n.value)==0){
return count;
}else{
if(n.getLeftTree()!=null){
t.push(n.getLeftTree());
count++;
}
if (n.getRightTree()!= null){
t.push(n.getRightTree());
count++;
}
}
}
return -1;
}
}发布于 2016-01-01 19:19:48
java泛型类型参数缺少<...>。
public int get(Comparable<?> element){
return getPosition(element, root);
}
private int getPosition(Comparable<?> element, TreeNode root) {
int count = 0;
if (root == null) {
return -1;
} else {
Stack<TreeNde> t = new Stack<>();
t.push(root);
while (!t.empty()) {
TreeNode n = t.pop();
if (element.compareTo(n.value) == 0) {
return count;
} else {
if (n.getLeftTree() != null) {
t.push(n.getLeftTree());
count++;
}
if (n.getRightTree() != null) {
t.push(n.getRightTree());
count++;
}
}
}
}
return -1;
}然而,该算法似乎没有将树的左侧部分计算到找到的元素。但是,如果位置不是排序元素中的索引,这可能是可以的。(我没有检查正确性,因为没有早期的<检查。)如果这是一个家庭作业,“带栈的非递归”,那就重写一个递归版本。可能是两个嵌套循环,并且比较-1和+1。
https://stackoverflow.com/questions/34554912
复制相似问题