如何解决在非二进制树中搜索
| 大家好, 我创建了一个不是二叉树的树。现在,我要搜索的是元素。主要内容如下:由于与二叉树相比,我没有比较的机会,因此我必须找到其他实现代码的方法。这是我的想法: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;
}
当然,该代码不起作用。困难的部分是我必须一找到就返回所搜索的值。但是,如果找不到,我仍然必须退货。我要怎么做???
解决方法
首先,您需要(以某种方式)使用对
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;
}
,您要查找的递归函数的元代码
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。