2011-05-05 48 views
0

BTNode<E>的的BST節點的每個具有雙號,我有以下字段:找到具有當前節點值的下一個值在二叉搜索樹

BTNode <E> root:一個指向樹的根

BTNode <E> current:一個指針到當前節點

我想要寫的方法下一頁(),使當前的點到具有當前節點值的下一值節點

這裏是WH在我已經做到目前爲止:

public boolean Next() 
    { 
     // List<E> tempList = new ArrayList<E>();  // Creating new list (I defined this at the begining of the class) 
     E tempValue = current.getElement();   // Gets the value of current element 
     makeSortedList(root);    // 
     E[] tempArray = (E[]) tempList.toArray();   // Convert the list to an array 
     int index = Arrays.binarySearch(tempArray, tempValue); // Find the position of current node value in the array 
     if(index >= count) // count is no. of nodes in the tree 
     { 
      E targetValue = tempArray[index + 1];   // Store the target value in a temporary variable 
      search(targetValue);       // This method searches for the node that has targetValue and make that node as the current node 
      return true; 
     } 
     else return false; 
    } 

    // This method takes the values of the tree and puts them in sorted list 
    private void makeSortedList(BTNode<E> myNode) 
    { 
     if(myNode != null) 
     { 
      makeSortedList(myNode.getLeft()); 
      tempList.add(myNode.getElement()); 
      makeSortedList(myNode.getRight()); 
     } 
    } 

你能幫我寫這個方法嗎?

+0

您的makeSortedList根本不做任何排序。 – Serhiy 2011-05-05 16:00:56

+0

我嘗試使用inorder traversal將其排序爲「樹排序技術」 – 2011-05-05 16:02:10

+0

錯誤是什麼? – 2011-05-05 16:03:40

回答

0

你是否檢查過Arrays.binarySearch()返回的索引是否是你期望的? 在調用它之前,元素也應該被排序。從代碼示例中可以看出,當在數組中找不到值時,如何處理該案例並不清楚。假設它總是在數組中,你爲什麼然後檢索值@ index + 1?

+0

我編輯的代碼,以便它處理時,值不在數組 – 2011-05-05 17:11:36

+0

btw,當我檢查代碼當前仍然是相同的,並沒有改變,也許makeSortedList()並不真正創建一個排序列表? – 2011-05-05 17:16:25