public TreeNode<City> search(City parent, TreeNode<City> t){
//As you guess, City class is irrelevant to the issue, I have no problem with City class.
if (t.getCity().equals(parent)) {
return t;
}
else if (t.hasLeftChild()){
search(parent,t.getLeftChild());
}
else if(t.hasNextSibling()){
search(parent,t.getNextSibling());
}
else//Since I know that case will never happen, the returned value is unimportant
return t;
}
当然,该代码不起作用。困难的部分是我必须在找到它后立即返回我正在搜索的值。然而,如果我找不到它,我仍然需要返回一些东西。我怎么会这样做?
答案 0 :(得分:0)
首先,您需要(以某种方式)使用递归调用search()
返回的值 - 可能是return
:
public TreeNode<City> search(City parent, TreeNode<City> t){
if (t.getCity().equals(parent)) {
return t;
}
else if (t.hasLeftChild()){
return search(parent,t.getLeftChild());
}
else if(t.hasNextSibling()){
return search(parent,t.getNextSibling());
}
return null;
}
答案 1 :(得分:0)
您正在寻找的递归函数的元代码
public TreeNode<City> search(City parent, TreeNode<City> t){
if (t.getCity().equals(parent)) {
return t;
}
if (t.hasLeftChild()) {
if (tmp = search(parent,t.getLeftChild())) {
return tmp;
}
}
if (t.hasnextSibling()) {
if (tmp = search(parent,t.getnextSibling())) {
return tmp;
}
}
return false;
}