Java 二叉搜索树

Java 二叉搜索树,java,algorithm,data-structures,binary-tree,Java,Algorithm,Data Structures,Binary Tree,下面是我查找某个元素位置的代码。我用二叉树来存储我的字典,我想知道为什么它会显示类似类型的警告。我必须在我的项目中使用它,其中元素是字符串类型 public int get(Comparable element){ return getPosition(element,root); } private int getPosition(Comparable element, TreeNode root){ int count = 0; if (root == null){

下面是我查找某个元素位置的代码。我用二叉树来存储我的字典,我想知道为什么它会显示类似类型的警告。我必须在我的项目中使用它,其中元素是字符串类型

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;
    }
}

java泛型类型参数丢失

public int get(可比较元素){
返回getPosition(元素,根);
}
私有int getPosition(可比较元素,树节点根){
整数计数=0;
if(root==null){
返回-1;
}否则{
堆栈t=新堆栈();
t、 推(根);
而(!t.empty()){
TreeNode n=t.pop();
if(元素比较(n.value)==0){
返回计数;
}否则{
如果(n.getLeftTree()!=null){
t、 push(n.getLeftTree());
计数++;
}
如果(n.getRightTree()!=null){
t、 推(n.getRightTree());
计数++;
}
}
}
}
返回-1;
}

但是,该算法似乎没有将树的左侧部分计算到找到的元素。但是,如果position不是已排序元素中的索引,则可以。(我没有检查正确性,因为没有早期的
Comparable是一个泛型类,它希望像
Comparable element
那样指定类型(这将返回从根开始的路径长度,而不是顺序遍历中的位置:您可能需要增加)
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;
}