亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用帶有 ArrayList 的 BST 的中序遍歷

使用帶有 ArrayList 的 BST 的中序遍歷

藍山帝景 2023-05-10 13:36:10
我正在完成一種作業方法,該方法使用字典中包含單詞的 BST 的中序遍歷。我了解如何使用遞歸來完成中序遍歷,但我無法將我的節點值包含在 ArrayList 中,這是該方法所必需的,因為每次該方法再次調用自身時,都會重新創建列表并重新創建所有其他以前的值丟失了。 /**   * Recursive Helper method that returns a list of all the words stored in the subtree rooted at   * current sorted alphabetically from A to Z   *    * @param current pointer to the current DictionaryWord within this dictionaryBST   * @return an ArrayList of all the words stored in the subtree rooted at current   */  private static ArrayList<String> getAllWordsHelper(DictionaryWord current) {    ArrayList<String> list = new ArrayList<String>();    if (current != null) {      getAllWordsHelper(current.getLeftChild());      list.add(current.getWord());      getAllWordsHelper(current.getRightChild());    }    return list;  }}返回一個包含值的 ArrayList 是必需的,我無法將其更改為將一個值作為參數傳入,因此我在解決此問題時遇到了一些麻煩 - 我在網上看到的所有其他示例僅打印當前節點。任何建議表示贊賞,謝謝!
查看完整描述

2 回答

?
呼如林

TA貢獻1798條經驗 獲得超3個贊

問題是您沒有對遞歸調用返回的值做任何事情。您需要將它們實際添加到列表中:


list.addAll(getAllWordsHelpers(current.getLeftChild()));

list.add(current.getWord();

list.addAll(getAllWordsHelpers(current.getRightChild()));

一種更有效的方法是將列表傳遞給方法,這樣您就不需要繼續創建新列表:


private void getAllWordHelpers(List<String> list, DictionaryWord current) {

    if (current != null) {

        getAllWordHelpers(list, current.getLeftChild());

        list.add(current.getWord());

        getAllWordHelpers(list, current.getRightChild());

    }

}


查看完整回答
反對 回復 2023-05-10
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

The problem is you want to store words across multiple call stacks during inorder traversal, which is possible only by using a global object which should be available to all call stacks during recursive calls.


So here we have used a formal argument called words which represent a list object and this object will be common to all call stacks during recursive calls.


ArrayList<String> words = getAllWordsHelper(current, null)



private static ArrayList<String> getAllWordsHelper(DictionaryWord current, List<String> words) {

    if(words == null) words = new ArrayList(); 


    if (current != null) {

      getAllWordsHelper(words, current.getLeftChild());

      list.add(current.getWord());

      getAllWordsHelper(words, current.getRightChild());

    }

    return words;

  }

}


查看完整回答
反對 回復 2023-05-10
  • 2 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號