0

I am attempting to implement an iterator class for my binary search tree. (to be more precise, it is a KD-Tree, but I don't think that will change things much). I want the iterator to follow an in-order traversal of the tree. I have an arrayList which contains the leaf nodes in this "in-order" order, and I would like the iterator to iterate through these leaf nodes in this order. How can I use this arrayList to implement next() method?

I have tried creating an int field called index in the Iterator class. Then my next() method would increment the index by 1 and return arrayList.get(index). However, this didn't seem to work.

Using the arrayList to implement next() isn't necessary, but it seemed like the easiest way. If there is a way to do this with the arrayList, that would be preferred. Is this even possible? If not, any advice whatsoever would be welcome! Thanks

5
  • 1
    You have an ArrayList holding all the nodes? This is strange if the data structure is supposed to be a binary search tree. Could you edit the question to include more details about what's in this ArrayList, and in what order? Commented Nov 15, 2019 at 3:46
  • The ArrayList contains only the leaf nodes, as in this case, the leaf nodes contain all the important data. Then I would like my iterator to be able to iterate through these leaf nodes. Commented Nov 15, 2019 at 3:52
  • 1
    What does it mean to do an in-order traversal over just the leaf nodes? If only the leaf nodes are processed, then either pre-order, in-order or post-order would process the leaf nodes in the same order. Does the ArrayList happen to contain the nodes in the right order already, by any chance? Commented Nov 15, 2019 at 3:56
  • Yes, that was why I made the ArrayList. The arrayList contains the elements in the order in which I wish to iterate them in. So regardless of "in-order", I simply want my next() method to follow the order of my ArrayList Commented Nov 15, 2019 at 4:35
  • 1
    So you can just write arrayList.iterator() to get an iterator, then. Commented Nov 15, 2019 at 4:41

1 Answer 1

1

You can create an iterator for the list using iterator() method.


        // Create and populate the list 
        ArrayList<String> list = new ArrayList<>(); 

        list.add("Hello"); 
        list.add("World");

        // Displaying the list 
        System.out.println("The list is: "+ list); 

        // Create an iterator for the list 
        // using iterator() method 
        Iterator<String> iter = list.iterator(); 

        while (iter.hasNext()) { 
            System.out.print(iter.next() + " "); 
        } 

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.