java在非二进制树中搜索
嘿,伙计们, 我创建了一个不是二叉树的树。现在,我想搜索一个元素。主要内容如下:由于我没有机会与二叉树进行比较,因此我必须找到一些其他方法来实现代码。下面是我的想法:
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;
}
当然,该代码不起作用。困难的部分是,我必须返回我正在搜索的值,只要我找到它。然而,如果我找不到它,我仍然必须归还一些东西。我该怎么做
# 1 楼答案
首先,您需要(以某种方式)使用对
search()
的递归调用返回的值——可能是return
it:# 2 楼答案
要查找的递归函数的元代码