Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二叉搜索树中迭代器的实现_Java_Generics_Binary Search Tree - Fatal编程技术网

Java 二叉搜索树中迭代器的实现

Java 二叉搜索树中迭代器的实现,java,generics,binary-search-tree,Java,Generics,Binary Search Tree,我通过在树上按顺序遍历来将树的键保存在数组中 我在函数private void inOrder(节点节点,K[]键,int counter)中使用counter变量,并将键添加到数组中,同时在每次添加后递增计数器变量。然而,问题是由于递归,计数器的值被重置为0。我还试着使计数器静态,但它使问题更加复杂,也无法解决问题 下面是完整的代码 package lab8; import java.util.Set; public interface Map61B<K, V> extends

我通过在树上按顺序遍历来将树的键保存在数组中

我在函数
private void inOrder(节点节点,K[]键,int counter)
中使用
counter
变量,并将键添加到数组中,同时在每次添加后递增计数器变量。然而,问题是由于递归,
计数器
的值被重置为0。我还试着使
计数器
静态,但它使问题更加复杂,也无法解决问题

下面是完整的代码

package lab8;
import java.util.Set;

public interface Map61B<K, V> extends Iterable<K> {
    /** Removes all of the mappings from this map. */
    void clear();

    /* Returns true if this map contains a mapping for the specified key. */
    boolean containsKey(K key);

    /* Returns the value to which the specified key is mapped, or null if this
     * map contains no mapping for the key. 
     */
    V get(K key);

    /* Returns the number of key-value mappings in this map. */
    int size();

    /* Associates the specified value with the specified key in this map. */
    void put(K key, V value);

    /* Returns a Set view of the keys contained in this map. */
    Set<K> keySet();    

    /* Removes the mapping for the specified key from this map if present.
     * Not required for Lab 8. If you don't implement this, throw an 
     * UnsupportedOperationException. */
    V remove(K key);

    /* Removes the entry for the specified key only if it is currently mapped to
     * the specified value. Not required for Lab 8. If you don't implement this,
     * throw an UnsupportedOperationException.*/
    V remove(K key, V value);
}

package lab8;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class BSTMap<K extends Comparable<K>,V> implements Map61B<K,V> {

    Node root;
    int size;

    class Node{
        K key;
        V value;
        Node left,right; 

        public Node(){}

        public Node(K k,V v){
            key=k;
            value=v;
        }
    }

    public BSTMap(){}


    /** Removes all of the mappings from this map. */
    public void clear(){
        root=null;
        size=0;
    }

    /* Returns true if this map contains a mapping for the specified key. */
    public boolean containsKey(K key){
        return get(key) != null;
    }

    /* Returns the value to which the specified key is mapped, or null if this
     * map contains no mapping for the key. 
     */
    public V get(K key){

        if(size()==0)
            return null;

        Node temp=root;
        //System.out.println("temp:"+temp+" "+temp.key);
        while(temp!=null){
            int comp=temp.key.compareTo(key);
            if(comp==0)
                return temp.value;
            else if(comp<0)
                temp=temp.left;
            else
                temp=temp.right;
        }
        return null;
    }

    /* Returns the number of key-value mappings in this map. */
    public int size(){
        return size;
    }


    //private recursive method
    private Node put(Node node,K key,V value){
        if(node==null)
            return new Node(key,value);
        int comp;
        comp=key.compareTo(node.key);
        if(comp==0)
            return node;
        else if(comp<0)
            node.left=put(node.left,key,value);
        else
            node.right=put(node.right,key,value);
        return node;
    }

    /* Associates the specified value with the specified key in this map. */
    public void put(K key, V value){
        root=put(root,key,value);
        size++;
        return;
    }



    public void printInOrder(){
        if(size()==0){
            System.out.println("list empty");
            return;
        }
        inOrder(root);

    }

    private void printNode(Node node){
        System.out.print("("+node.key+" "+node.value+")");
    }

    private void inOrder(Node node){
        if(node==null)
            return;
        inOrder(node.left);
        printNode(node);
        inOrder(node.right);
    }

    private void inOrder(Node node,Set keySet){
        if(node==null)
            return ;
        inOrder(node.left,keySet);
        //System.out.println("Adding key:"+node.key);
        keySet.add(node.key);
        inOrder(node.right,keySet);
    }

    private void inOrder(Node node,K[] keys,int counter){
        if(node==null)
            return ;
        inOrder(node.left,keys,counter);
        System.out.println("Adding key to array at location:"+counter+" key:"+node.key);
        keys[counter++]=node.key;
        inOrder(node.right,keys,counter);
    }

    public Set<K> keySet(){
        if(root==null)
            return null;
        Set<K> keys=new HashSet<K>();
        inOrder(root,keys);
        return keys;
    }    

    public V remove(K key){
        throw new UnsupportedOperationException();
    }

    public V remove(K key, V value){
        throw new UnsupportedOperationException();  
    }

    public  class KeyIterator implements Iterator<K>{
        private K[] keys;
        private int counter;

        public KeyIterator(){
            keys=(K[])new Comparable[size];
            //(K[])new Comparable[size];
            inOrder(root,keys,counter);

            System.out.println("Printing inside constrcutor");
            for(int i=0;i<keys.length;i++)
                System.out.print(keys[i]+" ");
            System.out.println();

        }

        public boolean hasNext(){
            return counter<keys.length;
        }

        public K next(){
            return keys[counter++];
        }
        public void remove(){

        }
    }

    public Iterator<K> iterator(){
        Iterator<K> seer=new KeyIterator();

        return seer;
    }

    public static void main(String[] args) {
        BSTMap<String, String> a = new BSTMap<String, String>();
        BSTMap<String, Integer> b = new BSTMap<String, Integer>();

        b.put("C", 1);
        System.out.println(b.get("C"));
        b.put("A", 2);
        b.put("B", 3);
        b.put("G", 4);
        b.printInOrder();
        System.out.println();
        System.out.println("keys are:"+b.keySet());

        System.out.println("Printing via enhanced for loop:");
        for(String str:b)
            System.out.println(str);

        //Above code is same as saying
        System.out.println("Printing the legendary iterator:");
        Iterator<String> seer=b.iterator();
        while(seer.hasNext()){
            System.out.println(seer.next());
        }

    }

}

我没有使用数组,而是使用了ArrayList,解决了这个问题。 前面代码的问题是,
计数器
在递归调用
inOrder
时用于重置为0,因为它是一个局部变量。 将其更改为数组列表使用
add()
函数消除了计数器变量,从而解决了问题 以下是相同的代码:-

import java.util.Set;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class BSTMap<K extends Comparable<K>,V> implements Map61B<K,V> {

    Node root;
    int size;

    class Node{
        K key;
        V value;
        Node left,right,parent; 

        public Node(){}

        public Node(K k,V v,Node p){
            //System.out.println(k+" "+v+" "+p);
            key=k;
            value=v;
            parent=p;
        }
    }


    public class KeyIterator implements Iterator<K>{
        private ArrayList<K> keys;
        private int counter;

        public KeyIterator(){
            counter=0;
            keys=new ArrayList<K>();
            inOrder(root,keys);

            System.out.println("KeyIterator()");
            for(K k:keys)
                System.out.print(k+" ");
            System.out.println();

        }

        public boolean hasNext(){
            return counter<keys.size();
        }

        public K next(){
            return keys.get(counter++);
        }
        public void remove(){

        }
    }

    public Iterator<K> iterator(){
     Iterator<K> seer=new KeyIterator();

     return seer;
 }


 public static void main(String[] args) {
     BSTMap<String, String> a = new BSTMap<String, String>();
     BSTMap<String, Integer> b = new BSTMap<String, Integer>();

     b.put("H", 1);
     b.put("D", 2);
     b.put("I", 3);
     b.put("B", 4);
     b.put("E", 5);
     b.put("A", 6);
     b.put("C", 7);
     b.put("F", 7);
     b.put("G", 7);
     b.put("L", 7);
     b.put("I", 7);
     b.put("J", 7);
     b.put("N", 7);
     b.put("M", 7);
     b.put("O", 7);

     Iterator<String> seer=b.iterator();
     while(seer.hasNext()){
         System.out.println(seer.next());
     }

 }
}
import java.util.Set;
导入java.util.ArrayList;
导入java.util.HashSet;
导入java.util.Iterator;
公共类BSTMap实现了Map61B{
节根;
整数大小;
类节点{
K键;
V值;
节点左、右、父节点;
公共节点(){}
公共节点(K,V,节点p){
//系统输出打印项次(k+“”+v+“”+p);
key=k;
值=v;
父母=p;
}
}
公共类KeyIterator实现了迭代器{
私有ArrayList密钥;
专用int计数器;
公钥迭代器(){
计数器=0;
keys=newarraylist();
顺序(根,键);
System.out.println(“KeyIterator()”);
用于(K:键)
系统输出打印(k+“”);
System.out.println();
}
公共布尔hasNext(){

return counter代码不完整,不允许复制问题。实际上代码非常大,所以我想只放相关的代码。将代码推到GitHub上,会在几分钟后发布链接这里是代码的链接--我已将第150行的代码更改为--keys=(K[])new Comparable[size];它似乎已经抑制了错误,但迭代器仍然不起作用,我正在使用inOrder()fn中的计数器变量保存数组中的项,但代码仍然有缺陷。我从github运行了代码,没有出现异常。
import java.util.Set;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class BSTMap<K extends Comparable<K>,V> implements Map61B<K,V> {

    Node root;
    int size;

    class Node{
        K key;
        V value;
        Node left,right,parent; 

        public Node(){}

        public Node(K k,V v,Node p){
            //System.out.println(k+" "+v+" "+p);
            key=k;
            value=v;
            parent=p;
        }
    }


    public class KeyIterator implements Iterator<K>{
        private ArrayList<K> keys;
        private int counter;

        public KeyIterator(){
            counter=0;
            keys=new ArrayList<K>();
            inOrder(root,keys);

            System.out.println("KeyIterator()");
            for(K k:keys)
                System.out.print(k+" ");
            System.out.println();

        }

        public boolean hasNext(){
            return counter<keys.size();
        }

        public K next(){
            return keys.get(counter++);
        }
        public void remove(){

        }
    }

    public Iterator<K> iterator(){
     Iterator<K> seer=new KeyIterator();

     return seer;
 }


 public static void main(String[] args) {
     BSTMap<String, String> a = new BSTMap<String, String>();
     BSTMap<String, Integer> b = new BSTMap<String, Integer>();

     b.put("H", 1);
     b.put("D", 2);
     b.put("I", 3);
     b.put("B", 4);
     b.put("E", 5);
     b.put("A", 6);
     b.put("C", 7);
     b.put("F", 7);
     b.put("G", 7);
     b.put("L", 7);
     b.put("I", 7);
     b.put("J", 7);
     b.put("N", 7);
     b.put("M", 7);
     b.put("O", 7);

     Iterator<String> seer=b.iterator();
     while(seer.hasNext()){
         System.out.println(seer.next());
     }

 }
}