2012-05-10 59 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); 
}