So our professor gave us a code as an example of Iterator design pattern. Here he implemented inorder traversal for Binary Tree with iterator. I cannot really understand HOW inorder traversal works here... Like we always call method addAllLeftChildren() and we never add right children... How would it work then? Could someone explain?
public class BinaryTree<T> {
static class BTNode<E> {
BTNode<E> left, right;
E data;
BTNode(BTNode<E> left, BTNode<E> right, E data) {
this.left = left; this.right = right; this.data = data;
}
}
// root of tree
BTNode<T> root;
...
Iterator<T> inorderIterator() { return new BTInorderIterator<T>(root); }
Iterator<T> preorderIterator() { return new BTPreoderIterator<T>(root); }
Iterator<T> postorderIterator() { return new BTPostorderIterator<T>(root); }
...
}
class BTInorderIterator<E> implements Iterator<E> {
Stack s;
BTInorderIterator(BinaryTree.BTNode<E> root) {
s = new Stack();
addAllLeftChildren(root);
}
void addAllLeftChildren(BinaryTree.BTNode<E> subtree) {
if (subtree == null) return;
s.push(subtree);
addAllLeftChildren(subtree.left);
}
public boolean hasNext() {
return !s.isEmpty();
}
public E next() {
BinaryTree.BTNode<E> t = s.pop();
addAllLeftChildren(t.right);
return t.data;
}
public void remove()
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
This is how I implemented the same logic but in different manner. Is it a good implementation comparing with the above one?
public class BTInorderIterator<T> extends BTIterator<T>{
public BTInorderIterator(BTNode<T> root){
this.root = root;
stack = new SStack<T>();
fillStack(root);
}
public void fillStack(BTNode<T> next){
if(next == null) return;
fillStack(next.right);
stack.push(next.data);
fillStack(next.left);
}
@Override
public T next() {
return stack.pop();
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
}
Aucun commentaire:
Enregistrer un commentaire