问题描述
我必须为二叉树实现自定义迭代器,“下一个方法”正在对二叉树进行排序。我不允许使用任何java.util包,因此不能为此使用堆栈。
@Override
public T next() {
T result = node.data;
if (node.rightChild != null) {
node = smallest(node.rightChild);
} else {
node = node.parent;
}
return result;
}
private Nodes<T> smallest(Nodes<T> n) {
if (n.leftChild != null) {
return smallest(n.leftChild);
} else {
return n;
}
}
此刻,他只是迭代直到没有更多rightChild为止。您能帮我完成“下一个方法”吗?
感谢大家
解决方法
经过大量测试,这是我的解决方案,效果很好。如果有人需要完整的代码,只需询问
@Override
public T next() {
T result = node.data;
if (node.rightChild != null) {
node = smallest(node.rightChild);
} else {
while (node.parent != null && node != node.parent.leftChild){
node = node.parent;
}
node = node.parent;
}
return result;
}
private Nodes<T> smallest(Nodes<T> n) {
if (n.leftChild != null) {
return smallest(n.leftChild);
} else {
return n;
}
}