Maxim
Maxim

Reputation: 231

Iterate through a avl tree

I currently write on an AVL-tree and write an iterator-method, to iterate through the whole tree in preorder. And I get a NullPointer if I process the line 'stack.empty()' and don't have a clue why. And 4 eyes do see it better than two ;). Thank you in beforehand for help in advance.

Code:

@Override
public Iterator<E> iterator() {

    return new Iterator<E>(){
        Node start;
        Node current;
        //          int counter;
        Stack<Node> stack;
        //          int border = count(root);

        public void iterator() {

            stack = new Stack<Node>();
            current = start;
            stack.add(root);
        }

        @Override
        public boolean hasNext() {
            if(stack.empty()) return false;
            else return true;
        }

        @Override
        public E next() {
            if(!hasNext()){
                throw new NoSuchElementException();
            }
            Node n = stack.pop();
            if(n.left.value != null) stack.push(n.left);
            if(n.right.value != null) stack.push(n.right);

            return  n.value;            
        }

    };
}

Upvotes: 0

Views: 1249

Answers (1)

Johannes
Johannes

Reputation: 2121

You probably mean n.left != null

Upvotes: 2

Related Questions