`
baby69yy2000
  • 浏览: 189783 次
  • 性别: Icon_minigender_1
  • 来自: 自己输入城市...
社区版块
存档分类
最新评论

InorderIterator类的实现

    博客分类:
  • Util
阅读更多
接口的定义:
public interface MyIterator<T> {
	public boolean hasNext();
	public T next();
}


实现接口:
package InorderIterator;

import TraverseTree.TNode;
import TraverseTree.TraverseTree;
import java.util.NoSuchElementException;
import java.util.Stack;

public class InorderIterator<T> implements MyIterator<T> {

	private Stack<TNode<T>> s = null;
	private TNode<T> curr = null;

	private TNode<T> goFarLeft(TNode<T> t) {
		if(t == null)
			return null;
		while(t.left != null) {
			s.push(t);
			t = t.left;
		}
		return t;
	}

	public InorderIterator(TNode<T> root) {
		s = new Stack<TNode<T>>();
		curr = this.goFarLeft(root);
	}

	public T next() {
		if(curr == null)
			throw new NoSuchElementException("no elements remaining!");
		//返回的值
		T value = curr.nodeValue;
		
		if(curr.right != null)
			curr = this.goFarLeft(curr.right);
		else if(!s.isEmpty())
			curr = (TNode<T>)s.pop();
		else
			curr = null;
		
		return value;
	}

	public boolean hasNext() {
		return curr != null;
	}

	public static void main(String[] args) {
		TNode<Character> root = TraverseTree.buildTree(0);
		MyIterator<Character> it = new InorderIterator<Character>(root);
		while(it.hasNext()) {
			char c = it.next();
			System.out.println(c);
		}
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics