在二叉树Java中查找并返回一个节点
嗨,我正试图找到一个等于参数给定的字符串的节点,并返回该节点。我的结构是字符串的二叉树。我们假设搜索的字符串存在 变量q被指定为树的根。(在函数中,我调用了find方法) 在find()函数的第4行中,不应返回对左子树的递归调用的结果。相反,如果从左子树得到“NULL”,则应该在右子树中搜索字符串 这是更新后的代码在二叉树Java中查找并返回一个节点,java,search,tree,binary-tree,Java,Search,Tree,Binary Tree,嗨,我正试图找到一个等于参数给定的字符串的节点,并返回该节点。我的结构是字符串的二叉树。我们假设搜索的字符串存在 变量q被指定为树的根。(在函数中,我调用了find方法) 在find()函数的第4行中,不应返回对左子树的递归调用的结果。相反,如果从左子树得到“NULL”,则应该在右子树中搜索字符串 这是更新后的代码 private NodeTree find(NodeTree q, String cont){ if(q==NULL) return NULL; if(q._contin
private NodeTree find(NodeTree q, String cont){
if(q==NULL) return NULL;
if(q._contingut.equals(cont)) return q;
NodeTree result = NULL;
if(!q._left) result = find(q._left,cont);
if(!result && q._right) result = find(q._right,cont);
return result;
}
如果您的BST构建正确,则需要决定将当前节点值与查询值进行比较的位置(左或右子树),如:
NodeTree find(NodeTree q, String query) {
if(q.value.equals(query))
return q;
else if (q.value.compareTo(query) > 0)
return q.left == null ? null : find(q.left, query);
else
return q.right == null ? null : find(q.right, query);
}
你有什么问题?--编辑:明白了。不返回find(q.\u左,续)。因为你的算法只能通过“左节点”。它不能正常工作。你这是什么意思:!q、 你走了!结果如何?
NodeTree find(NodeTree q, String query) {
if(q.value.equals(query))
return q;
else if (q.value.compareTo(query) > 0)
return q.left == null ? null : find(q.left, query);
else
return q.right == null ? null : find(q.right, query);
}