如何在二叉树中查找节点并返回?
我试图在二叉树中搜索一个节点,如果存在则返回,否则返回 null。顺便说一句,节点类有一个方法 name() ,它返回一个带有其名称的字符串......到目前为止我所拥有的是:
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;
}
这是正确的吗?
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;
}
Is this correct??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
如果结果不为空,您需要确保对搜索的递归调用返回。
像这样的东西应该有效......
You need to make sure your recursive calls to search return if the result isn't null.
Something like this should work...
由于语言对于这个问题来说并不重要,因此 C# 中的前序遍历看起来如下:
Since language doesn't matter much for this question, here's what it looks in C# with pre-order traversal:
如果在 node.left 或 node.right 中找到某些内容,则应该返回该内容
所以 else 块应该是这样的:
you should return something if it is found in node.left or node.right
so the else block should be something like that:
您不对递归调用的结果执行任何操作
you don't do anything with the result of the recursive calls
这可能会更好:
This might be better:
实际上,尽量避免递归。
如果你有大的树结构,你会得到堆栈溢出错误。
您可以使用列表代替:
Actually, try to avoid recursivity.
In case you have big tree structure you will get stack overflow error.
Instead of this you can use a list:
在 GitHub 上查看代码
View Code on GitHub
对于 C++ 人员:
For C++ guys: