如何在树中搜索节点并返回它? [英] How to search for a node in a tree and return it?
本文介绍了如何在树中搜索节点并返回它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在二叉树中搜索节点并在其存在的情况下返回,否则返回null。顺便说一下,节点类有一个方法名()返回一个带有它名字的字符串......到目前为止我所拥有的是:
I'm trying to search for a node in a binary tree and return in case it's there, otherwise, return null. By the way, the node class has a method name() that return a string with it's name...What I have so far is:
private Node search(String name, Node node){
if(node != null){
if(node.name().equals(name)){
return node;
}
else{
search(name, node.left);
search(name, node.right);
}
}
return null;
}
这是正确的吗?
推荐答案
如果结果不为null,您需要确保对搜索的递归调用返回。
You need to make sure your recursive calls to search return if the result isn't null.
类似于这应该工作...
Something like this should work...
private Node search(String name, Node node){
if(node != null){
if(node.name().equals(name)){
return node;
} else {
Node foundNode = search(name, node.left);
if(foundNode == null) {
foundNode = search(name, node.right);
}
return foundNode;
}
} else {
return null;
}
}
这篇关于如何在树中搜索节点并返回它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文