2012-05-10 91 views
2

即時通訊嘗試在java中編寫遞歸函數,它需要一個按字母順序排列的充滿單詞的數組列表,並儘可能地填充樹。據我所知,問題在於java沒有通過引用傳遞,所以在遞歸函數中,我從來沒有實際更新樹的左右分支指向的位置,這意味着樹的頂部永遠不會指向任何東西。有沒有更好的(工作)方式來做到這一點?我是否完全錯過了標誌,試圖首先填充樹?在java中用字典填充二叉樹的遞歸函數

public void saveNode(BinaryTreeNode parent, int left, int right) 
{ 
    int middle = (int) Math.ceil(((double)(right-left))/2.0); 
    int curIndex; 
    curIndex = middle+left; 

    parent = new BinaryTreeNode(words.get(curIndex)); 

    if(middle != 1) 
    { 
     saveNode(parent.left, left, curIndex); 
     saveNode(parent.right, curIndex, right); 
    } 
} 

PS:我是比較新的的Java

回答

1

你的問題是,當你執行

parent = new BinaryTreeNode(words.get(curIndex)); 

那請問值賦給parent至於呼叫者有關,所以它不會傳播回調用堆棧。

你想要的代碼看起來像這樣(取出的問題不相關的代碼):

public static void main(String[] args) { 
    // keep a reference to the root node so you can access the tree after loading 
    BinaryTreeNode root = new BinaryTreeNode(); 
    // pass the root node into the first call to the recursive method 
    saveNode(root, left, right); 
} 

public void saveNode(BinaryTreeNode parent, int left, int right) { 
    // keep building your tree as you descend into it 
    parent.left = new BinaryTreeNode(); 
    parent.right = new BinaryTreeNode(); 
    // pass the (new) branches into deeper calls  
    saveNode(parent.left, left, curIndex); 
    saveNode(parent.right, curIndex, right); 
}