1 / 8

Binary Tree Iterators

Binary Tree Iterators. Tree Traversals: preorder, inorder, postorder public interface java.util.Iterator<E> boolean hasNext() E next() void remove() /*optional – removes the last E returned by the

aolani
Download Presentation

Binary Tree Iterators

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Binary Tree Iterators Tree Traversals: preorder, inorder, postorder public interface java.util.Iterator<E> boolean hasNext() E next() void remove() /*optional – removes the last E returned by the Iterator in the underlying Collection */

  2. Binary Tree Iterators • Implementations often maintain a linear structure that keeps track of the state of tht iterator. java.util.Stack<E> boolean empty() E pop() E push(E)

  3. Inorder Iterator • When is each node visited? • After all of the nodes in its left subtree have been visited and before • Any of the nodes of the right subtree

  4. Inorder Iterator – 1 8 6 12 4 11 17 2 5 10 20 1 3 The first element visited in an in-order traversal is the left-most descendant of the root. To initialize the iterator: push each of the nodes from the root down to the leftmost descendant on the stack.

  5. Inorder Iterator – 2 8 6 12 4 11 17 2 5 10 20 1 3 tos 1 2 4 6 8

  6. Inorder Iterator – 3 • next() • Returns the current value • Increments the iterator BTN<E> current = stack.pop(); E value = current.getValue(); • What do we know about current in the tree? • All left children have been visited • It may or may not have a right subtree

  7. Inorder Iterator - 4 • Two cases: • If current has no right subtree, we are done. The next node to be considered is at the top of the stack. • If current has a right subtree: • Those nodes haven't been visited • They are not on the stack ...so... • Push the right child and each of the right child's left descendants on the stack.

  8. Inorder Iterator – 5 current 8 before: 12 tos: empty 11 17 10 20 tos after: 10 11 12

More Related