第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

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

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

藍(lán)山帝景 2023-05-10 13:36:10
我正在完成一種作業(yè)方法,該方法使用字典中包含單詞的 BST 的中序遍歷。我了解如何使用遞歸來(lái)完成中序遍歷,但我無(wú)法將我的節(jié)點(diǎn)值包含在 ArrayList 中,這是該方法所必需的,因?yàn)槊看卧摲椒ㄔ俅握{(diào)用自身時(shí),都會(huì)重新創(chuàng)建列表并重新創(chuàng)建所有其他以前的值丟失了。 /**   * 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;  }}返回一個(gè)包含值的 ArrayList 是必需的,我無(wú)法將其更改為將一個(gè)值作為參數(shù)傳入,因此我在解決此問(wèn)題時(shí)遇到了一些麻煩 - 我在網(wǎng)上看到的所有其他示例僅打印當(dāng)前節(jié)點(diǎn)。任何建議表示贊賞,謝謝!
查看完整描述

2 回答

?
呼如林

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊

問(wèn)題是您沒(méi)有對(duì)遞歸調(diào)用返回的值做任何事情。您需要將它們實(shí)際添加到列表中:


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

list.add(current.getWord();

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

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


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

    if (current != null) {

        getAllWordHelpers(list, current.getLeftChild());

        list.add(current.getWord());

        getAllWordHelpers(list, current.getRightChild());

    }

}


查看完整回答
反對(duì) 回復(fù) 2023-05-10
?
喵喵時(shí)光機(jī)

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊

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;

  }

}


查看完整回答
反對(duì) 回復(fù) 2023-05-10
  • 2 回答
  • 0 關(guān)注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)