Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Tree Iterators Tree Traversals: preorder, inorder, postorder

Similar presentations


Presentation on theme: "Binary Tree Iterators Tree Traversals: preorder, inorder, postorder"— 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 */ Bailey 11.6

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 BT<E> currrent = root;
8 6 12 4 11 17 2 5 10 20 1 3 tos BT<E> currrent = root; while (current != null) { stack.push(current); current = current.left; }

6 Inorder Iterator – 3 next() What do we know about current in the tree?
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:


Download ppt "Binary Tree Iterators Tree Traversals: preorder, inorder, postorder"

Similar presentations


Ads by Google