简体   繁体   English

Java中的递归函数以字典填充二叉树

[英]Recursive function in java to fill binary tree with dictionary

im trying to write a recursive function in java where it takes an arraylist full of words in alphabetical order and fills up the tree as best it can. 我试图在Java中编写一个递归函数,该函数需要一个按字母顺序排列的单词数组列表,并尽最大可能填充树。 As far as I can tell, the problem im having is that java doesnt pass by reference, so in my recursive function, I never actually update where the trees left and right branches point, meaning the top of the tree never points to anything. 据我所知,问题在于java不会通过引用传递,因此在我的递归函数中,我从未真正更新树左右分支指向的位置,这意味着树的顶部永远不会指向任何东西。 Is there a better (working) way to do this? 有没有更好的(可行的)方法来做到这一点? Am I missing the mark completely in my attempt to fill the tree in the first place? 我是不是一开始就完全想不到树的标记?

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: I'm relatively new to java PS:我对Java比较陌生

Your problem is that when you execute 你的问题是当你执行

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

That does not assign a value to parent as far as the caller is concerned, so it doesn't get propagated back up the call stack. 并不一个值分配给parent至于呼叫者而言,所以它不会传播回调用堆栈。

You want to code to look something like this (taking out code not relevant to the problem): 您希望代码看起来像这样(删除与问题无关的代码):

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM