Publicidad

25-10 (Preorder iterator) Add the following method in the BST class th.docx

todd621
8 de Feb de 2023
25-10 (Preorder iterator) Add the following method in the BST class th.docx
Próximo SlideShare
Note- Help with methods public boolean remove(Object o)- public boolea.pdfNote- Help with methods public boolean remove(Object o)- public boolea.pdf
Cargando en ... 3
1 de 1
Publicidad

Más contenido relacionado

Similar a 25-10 (Preorder iterator) Add the following method in the BST class th.docx(20)

Más de todd621(20)

Publicidad

25-10 (Preorder iterator) Add the following method in the BST class th.docx

  1. 25.10 (Preorder iterator) Add the following method in the BST class that returns an iterator for traversing the elements in a BST in preorder. /** Returns an iterator for traversing the elements in preorder */ java.util.IteratorpreorderIterator() Solution class BTPreorderIterator extends AbstractIterator { /** * The root of the subtree to be considered by traversal. */ protected BinaryTree root; // root of tree to be traversed /** * The stack that maintains the state of the iterator. */ protected Stack > todo; // stack of unvisited nodes whose /** * Constructs a pre-order traversal of subtree rooted at root. * * @post constructs an iterator to traverse in preorder * * @param root Root of subtree to be traversed. */ public BTPreorderIterator(BinaryTree root) { todo = new StackList >(); this.root = root; reset(); } /** * Resets the iterator to the first node of the traversal. * * @post resets the iterator to retraverse */ public void reset() { todo.clear(); // stack is empty; push on root if (root != null) todo.push(root); } /** * Returns true if some nodes of subtree have yet to be considered. * * @post returns true iff iterator is not finished * * @return True iff more nodes to be considered in traversal. */ public boolean hasNext() { return !todo.isEmpty(); } /** * Returns the value currently being referenced by iterator. * * @pre hasNext() * @post returns reference to current value * * @return The current value. */ public E get() { return todo.get().value(); } /** * Returns the current value and increments the iterator. * Iterator is then incremented. * * @pre hasNext(); * @post returns current value, increments iterator * * @return The value currently being considered. */ public E next() { BinaryTree old = todo.pop(); E result = old.value(); if (!old.right().isEmpty()) todo.push(old.right()); if (!old.left().isEmpty()) todo.push(old.left()); return result; } }
Publicidad