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;
}
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.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.