Question

I've written a recursive method that should return a tree node which fits a specific course. The method works great but instead of returning the value it returns only null. Any idea how to solve it? Here is the code:

private TrieNode<String,V> prefix_last_child(TrieNode<String,V> STN , String prefix) {
    if (prefix.equals("")) {
        return STN;
    }
    char[] preffixx = prefix.toCharArray();
    if (STN.getNexts().get(alphabet_place(preffixx[0])) == null) {
        return null;
    }
    if (!prefix.equals(""))
        prefix_last_child(STN.getNexts().get(alphabet_place(preffixx[0])), prefix.substring(1));
    return null;
}
Was it helpful?

Solution

Your code is very close to working correctly. Here is the problem:

if (!prefix.equals(""))
    // You make a recursive invocation, and then...
    prefix_last_child(STN.getNexts().get(alphabet_place(preffixx[0])), prefix.substring(1));
// ...ignore its return value, and return null instead!
return null;

Replace with

if (!prefix.equals(""))
    return prefix_last_child(STN.getNexts().get(alphabet_place(preffixx[0])), prefix.substring(1));
//  ^^^^^^
return null;

to fix the problem.

OTHER TIPS

You are only ever returning null or the constant STN from the function. There is no way a meaningful/non-fixed value can even be returned.

to write a recursive method, replace

 if (!prefix.equals(""))
        prefix_last_child(STN.getNexts().get(alphabet_place(preffixx[0])), prefix.substring(1));

with if (!prefix.equals("")) return prefix_last_child(STN.getNexts().get(alphabet_place(preffixx[0])), prefix.substring(1));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top