1
嘗試以無序方式遍歷二叉樹時,它會打印根,最右邊的子元素,然後停止。有些東西顯然是錯誤的,而我在繞過這個方面遇到了困難,因爲我對樹型結構很陌生。我究竟做錯了什麼?爲什麼我的二叉樹迭代器停止了?
主要:
while (tree.iterator().hasNext())
System.out.println(tree.iterator().next());
迭代:
public Iterator<T> iterator() {
Iterator<T> it = new Iterator<T>() {
Node<T> next = root;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
System.out.println("Returning data");
T r = next.data;
if (next.right != null) {
next = next.right;
while (next.left != null)
next = next.left;
} else while (true) {
if (next.parent == null) {
next = null;
return r;
}
if (next.parent.left == next) {
next = next.parent;
return r;
}
next = next.parent;
}
return r;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
};
return it;
}
輸出:
242
275
279
283
242是樹的根。
242.left = 33
242.right = 283
更新1:
樹:
242
|33
||29
|||25
||||NULL
||||NULL
|||NULL
||74
|||70
||||66
|||||NULL
|||||NULL
||||NULL
|||115
||||111
|||||107
||||||NULL
||||||NULL
|||||NULL
||||156
|||||152
||||||148
|||||||NULL
|||||||NULL
||||||NULL
|||||197
||||||193
|||||||NULL
|||||||NULL
||||||238
|||||||234
||||||||NULL
||||||||NULL
|||||||NULL
|283
||279
|||275
||||NULL
||||NULL
|||NULL
||NULL
你說的「選擇訂單」是什麼意思? – krystah
我的不好,我誤解了這裏的「inorder」術語;) – Joffrey
任何想法,我應該這樣做?對於匿名迭代器類來說顯然是一個工作,但是在哪裏呢?沒有提及「最左邊的節點」,所以我必須做一個while(next.left!= null)next = next.left;'thing。 – krystah