InorderIterator类的实现

接口的定义:
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);
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值