java - 如何在 AVL 树中查找特定值并返回 Node
问题描述
public Node search_data_var2(Comparable searchable, Node T){
if(T.getInfo()==searchable){
return(T);
}
else{
if(T.getInfo()==null){
return null;
}
if(T.getInfo().compareTo(searchable)>0){
search_data_var2(searchable,T.getLeft());
}
if(T.getInfo().compareTo(searchable)<0){
search_data_var2(searchable,T.getRight());
}
}
}
我需要创建一个方法来查找具有特定值“可搜索”的节点并在它包含节点时返回节点“T”。如果这样的值不存在,该函数应返回“null”。但是我遇到了麻烦,不知道如何用一种方法来实现这一点。上面的函数是我写的。问题是该方法不能以相同的方式返回 Node 和 null。
不禁止使用外部函数来实现这一点,但目前我不知道如何实现这一点。
解决方案
出于查找目的,AVL 树与普通的二叉搜索树相同。
您的代码几乎就在那里!大多数情况下,您只需要return
在递归调用之前添加关键字。
以下是我还将进行的其他一些更改:
- 按照 Java 中
T
的约定,用于泛型类型。我会将节点重命名为更具描述性的名称(例如node
)。 - 我不会检查引用相等 (
==
),而是使用该方法检查值相等,因为无论如何compareTo
您都在使用。compareTo
这使您无需参考即可找到所需的值。 - 我会将 null 检查移到方法的顶部,以避免出现
NullPointerException
.
public Node search_data_var2(Comparable searchable, Node node) {
// If node is null, we've run off the end of the tree
// Therefore, the value is not contained in the tree - return null
if (node == null || node.getInfo() == null) {
return null;
}
if (node.getInfo().compareTo(searchable) == 0) {
// This node has info equal to the search condition - return it!
return node;
} else if (node.getInfo().compareTo(searchable) > 0) {
// The sought value must be in the left subtree - start the search again there
return search_data_var2(searchable, node.getLeft());
} else if (node.getInfo().compareTo(searchable) < 0) {
// The sought value must be in the right subtree - start the search again there
return search_data_var2(searchable, node.getRight());
}
}
推荐阅读
- sharepoint - 如何使用 Microsoft Graph 或 SharePoint API 获取每个 SharePoint 网站的大小?
- c++ - C++ 构造函数查询
- javascript - 在jquery中撤消mouseleave上的substr函数
- c# - 我的 mySQL Delete 命令无法正常工作
- .net - 如何使用 MimeKit 从电子邮件中排除签名和引用部分?
- twilio - 在 twilio 函数中获取回调函数错误
- php - LARAVEL Eloquent: BelongsTo 关系 - 批量更新
- amazon-web-services - 不使用 .htaccess 的新 Elastic Beanstalk 实例
- r - 如何计算两个日期之间的持续时间
- javascript - 如何使用自定义 Axios 实例取消令牌?