Max
Max

Reputation: 59

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. 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. 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

Upvotes: 2

Views: 1543

Answers (1)

Bohemian
Bohemian

Reputation: 425188

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.

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

Upvotes: 1

Related Questions