我正在寻找搜索二叉树以查找存储在节点中的字符串。
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 。