Java BinarySearchTrees: entrada del valor de la tecla de retorno (de búsqueda)

votos
0

Estoy tratando de implementar una interfaz de base de datos utilizando BSTs. Tengo una BTSEntry clase interna que representa un nodo con variables clave, el valor y los nodos de izquierda / derecha. Cada nodo de la izquierda es menor (en orden alfabético) que su padre, mientras que cada nodo de la derecha es más grande que su padre.

El primer problema es que no sé lo que es el nextNode () en la clase interna Entrada supone que es. ¿Es simplemente el nodo correcto? O es lo que he hecho a continuación?

private BinarySearchTreeEntry getLeftMost() {
        BinarySearchTreeEntry n = this;
        while (n.left != null) {
            n = n.left;
        }
        return n;
    }

    public BinarySearchTreeEntry getNext() {
        if (right != null) {
            return right.getLeftMost();
        } else {
            BinarySearchTreeEntry n = this;
            while (n.parent != null && n == n.parent.right) {
                n = n.parent;
            }
            return n.parent;
        }
    }

El segundo problema es que no se sabe muy bien cómo poner en práctica el Int valor get (clave Str) método. EDIT: He tratado de hacer el método get (clave). ¿Es correcto? Se recursividad trabajo para esto?

public Integer get(String key) throws NoSuchElementException {
    BinarySearchTreeEntry curr = root;
    if(curr == null){
        return null;
    } else if(curr.getKey().equals(key)){
        return curr.getValue();
    } else if(key.compareTo(curr.getKey()) < 0){
        curr = curr.getLeft();
        get(key);
    } else{
        curr = curr.getRight();
        get(key);
    }

    return null;
}

Aquí es lo que he hecho hasta ahora. Cualquier ayuda sería muy apreciada! :)

    package database;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

public class BinarySearchTree<K, V> implements Dictionary<String, Integer> {

    private class BinarySearchTreeEntry 
    implements DictionaryEntry<String, Integer>{    
        private String key;
        private Integer value;
        private BinarySearchTreeEntry left;
        private BinarySearchTreeEntry right;
        private BinarySearchTreeEntry parent;

        BinarySearchTreeEntry(String key, Integer value, 
        BinarySearchTreeEntry left, 
        BinarySearchTreeEntry right) {
            this.key = key;
            this.value = value;
            this.left = left;
            this.right = right;
            if (left != null) left.parent = this;
            if (right != null) right.parent = this;
        }
        private BinarySearchTreeEntry getLeftMost() {
            BinarySearchTreeEntry n = this;
            while (n.left != null) {
                n = n.left;
            }
            return n;
        }

        private BinarySearchTreeEntry getRightMost() {
            BinarySearchTreeEntry n = this;
            while (n.right != null) {
                n = n.right;
            }
            return n;
        }


        public BinarySearchTreeEntry getNext() {
            if (right != null) {
                return right.getLeftMost();
            } else {
                BinarySearchTreeEntry n = this;
                while (n.parent != null && n == n.parent.right) {
                    n = n.parent;
                }
                return n.parent;
            }
        }

        public String getKey() {

            return key;
        }

        public Integer getValue() {

            return value;
        }

        public BinarySearchTreeEntry getLeft() {
            return left;
        }

        public BinarySearchTreeEntry getRight() {
            return right;
        }

    }

    private class ListIterator
    implements Iterator<DictionaryEntry<String, Integer>>  {

        private BinarySearchTreeEntry current;
        Stack<BinarySearchTreeEntry> workList;

        public ListIterator(BinarySearchTreeEntry entry){
            current = entry;
        }

        public boolean hasNext() {
            return current != null;
        }


        public BinarySearchTreeEntry next() {
            BinarySearchTreeEntry result = null;
            current = root;

            while(current!=null){
                workList.push(current);
                current = current.getLeft();
            }

            if(!workList.isEmpty()){
                result = (BinarySearchTreeEntry) workList.pop();
                current = result.getRight();
            }
            return result;
        }

        public void remove() {

        }

    }

    private BinarySearchTreeEntry root;
    private int items;

    public BinarySearchTree(){
        root = null;
        items = 0;
    }

    public int size() {
        ListIterator iter = iterator();
        while(iter.hasNext()){
            items += 1;
        }
        return items;
    }

    public boolean isEmpty() {

        return size() == 0;
    }

    public Integer get(String key) throws NoSuchElementException {
        BinarySearchTreeEntry curr = root;
        if(curr == null){
            return null;
        } else if(curr.getKey().equals(key)){
            return curr.getValue();
        } else if(key.compareTo(curr.getKey()) < 0){
            //Now what?
        }
        return null;
    }


    public void put(String key, Integer value) {

    }

    public void clear() {
        ListIterator iter = iterator();
        BinarySearchTreeEntry  curr;
        curr = root;
        while(iter.hasNext()){
            remove(curr.getKey());
            curr = iter.next();
        }
        remove(curr.getKey());
    }

    public void remove(String key) throws NoSuchElementException {


    }

    public ListIterator iterator() {
        return (new ListIterator(root));
    }


}
Publicado el 13/03/2011 a las 21:04
fuente por usuario
En otros idiomas...                            


1 respuestas

votos
0

No sé exactamente lo que se supone que su método getNext () para hacer, pero supongo que debe recibir el elemento más grande siguiente. Si ese es el caso, entonces parece que lo que está haciendo es correcto.

Sobre la segunda pregunta, no, la recursividad no funcionará. Usted (probablemente) que desee utilizar un bucle que va hasta que el nodo actual tiene la llave que busca (y devolver el valor al igual que está haciendo), o hasta que no hay un nodo de la izquierda o la derecha, dejando a comprobar (el nodo curr es nulo). Además, en base a la cabecera del método, parece que tendrá que lanzar una excepción si la llave no se encuentra en lugar de devolver nulo. Parece que usted tiene las condiciones adecuadas, sólo necesita algunos cambios menores en lo que hace cuando se cumplen esas condiciones.

Respondida el 13/03/2011 a las 23:41
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more