java使用递归搜索二叉树并检查它是否包含字符串
我试图使用递归搜索二叉树,并根据二叉树是否包含字符串返回true或false。这是我的密码
public class BinaryTree {
private String data;
private BinaryTree leftChild;
private BinaryTree rightChild;
public BinaryTree() {
data = null;
leftChild = null;
rightChild = null;
}
public BinaryTree(String d) {
data = d;
leftChild = new BinaryTree();
rightChild = new BinaryTree();
}
// This constructor is unchanged
public BinaryTree(String d, BinaryTree left, BinaryTree right) {
data = d;
leftChild = left;
rightChild = right;
}
// Get methods
public String getData() {
return data;
}
public BinaryTree getLeftChild() {
return leftChild;
}
public BinaryTree getRightChild() {
return rightChild;
}
// Set methods
public void setData(String d) {
data = d;
}
public void setLeftChild(BinaryTree left) {
leftChild = left;
}
public void setRightChild(BinaryTree right) {
rightChild = right;
}
public boolean contains(String d) {
return d != null && (this.getData().equals(d) ||
contains(this.getLeftChild().getData()) ||
contains(this.getRightChild().getData()));
}
所以,我的问题是contains方法,因为它一直给我一个stackoverflow。错误我希望我能提前得到这方面的帮助
# 1 楼答案
你可以试试这个:
# 2 楼答案
在每次递归调用中
this
引用同一对象,因此您不断地反复传递相同的值。您需要将BinaryTree
引用作为参数传递main(public)
contains
需要将要搜索的字符串和根传递给上述方法# 3 楼答案
你在那里做的不是递归。你在问:
对吧?
您的代码将其扩展为
左边是哪里
它根本没有将候选字符串与左侧数据进行比较,而是扩展到
这会导致无止境的循环,导致堆栈溢出
你应该把这门课改成
然后,您的树将成为根节点,搜索可以是递归的