2014-04-09 41 views
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 

回答

2

你似乎開始右側在去到最左邊的孩子之前的根。所以你想念整個左邊的部分開始。

您應該用最左邊的孩子初始化next,而不是根。

更新:你可以做的是,在初始化塊,像這樣:

Iterator<T> it = new Iterator<T>() { 

    Node<T> next; 

    { 
     next = root; 
     while (next.left != null) 
      next = next.left; 
    } 

    @Override 
    public boolean hasNext() { 
     return next != null;  
    } 

    //... 
} 
+0

你說的「選擇訂單」是什麼意思? – krystah

+0

我的不好,我誤解了這裏的「inorder」術語;) – Joffrey

+0

任何想法,我應該這樣做?對於匿名迭代器類來說顯然是一個工作,但是在哪裏呢?沒有提及「最左邊的節點」,所以我必須做一個while(next.left!= null)next = next.left;'thing。 – krystah