80 likes | 201 Views
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
E N D
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 */
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)
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
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.
Inorder Iterator – 2 8 6 12 4 11 17 2 5 10 20 1 3 tos 1 2 4 6 8
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
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.
Inorder Iterator – 5 current 8 before: 12 tos: empty 11 17 10 20 tos after: 10 11 12