Binary Tree Iterators Tree Traversals preorder inorder postorder
Binary Tree Iterators Tree Traversals: preorder, inorder, postorder public interface java. util. Iterator<E> boolean has. Next() 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 2 1 11 5 10 17 20 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 2 1 11 5 3 tos 1 2 4 6 8 10 17 20
Inorder Iterator – 3 next() Returns the current value Increments the iterator BTN<E> current = stack. pop(); E value = current. get. Value(); 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: 1. If current has no right subtree, we are done. The next node to be considered is at the top of the stack. 2. 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 11 10 tos: empty 17 20 after: tos 10 11 12
- Slides: 8