我正在搜索二叉树以查找存储在节点中的字符串。
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。
最佳答案
您正在调用遍历函数,而不向其传递要搜索的字符串...在很多情况下,您还缺少返回值。
您需要更多地考虑函数何时应终止递归(在这种情况下,返回节点)以及函数在不终止但探索树的其余部分时应执行的操作。
例如用伪代码(您进行编程):
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
}
关于java - 在二叉树中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502078/