Java 在二叉树中搜索字符串
我正在寻找一个二叉树来查找存储在节点中的字符串Java 在二叉树中搜索字符串,java,Java,我正在寻找一个二叉树来查找存储在节点中的字符串 public void traverse (BinaryTreeNode root){ if (root.leftchild != null){ traverse (root.leftchild); } System.out.println(root.character); if (root.rightchild != null){ traverse (root.rightc
public void traverse (BinaryTreeNode root){
if (root.leftchild != null){
traverse (root.leftchild);
}
System.out.println(root.character);
if (root.rightchild != null){
traverse (root.rightchild);
}
}
这可以很好地工作,并显示树中的所有节点。(该代码是从另一个旧的stackoverflow问题的代码中提取出来的!我的问题是如何将root.character与输入的字符串进行比较,以及它是否与中断递归匹配。如果有人能给出一些提示,我将不胜感激
public BinaryTreeNode traverse (BinaryTreeNode root, String inString){ // Each child of a tree is a root of its subtree.
if (root.character != null) {
if (root.character.equalsIgnoreCase(inString)) {
System.out.println("root.charcter: " + root.character + " char " + inString);
return root;
}
}
if (root.leftchild != null){
traverse (root.leftchild, inString);
}
if (root.rightchild != null){
traverse (root.rightchild, inString);
}
return null;
}
上面的代码似乎可以工作,它返回正确的BinaryTreeNode。但是,我还没有弄清楚如何在找到节点后停止递归,因此它也会在结尾返回null。您调用遍历函数时没有将字符串传递给它进行搜索……在很多情况下,您还缺少返回值 您需要更多地考虑函数何时应该终止递归(在这种情况下,返回节点),以及函数在不终止而是探索树的其余部分时应该做什么 e、 g.在伪代码中(您进行编程):
在Java中不要使用string==otherString,使用string.equals(otherString)。是的,这是伪代码,如果它不起作用,请返回您的实现并征求建议。感谢您的sudo代码。我已更新了代码。我已将原始问题中的代码更新为目前的代码。它可以工作并返回正确的节点,但无法停止代码中的递归,因此返回最后也是空的。
findNode(root, query) {
// nothing to search, not found
if root==null return null
// Found it!
if root.name==query return root
// This is when we recurse left, stop if we found a result
leftResult = findNode(root.left, query)
if leftResult!=null return leftResult
// else try to the right, stop if we found a result
rightResult = findNode(root.right, query)
if rightResult!=null return rightResult
// Nothing else to try, not found
return null
}