【发布时间】:2020-12-09 16:54:55
【问题描述】:
我有一个从文本文件中填充的二叉搜索树
当我显示 BST 时,它看起来像这样
the
in was
Minnesota it -- --
-- -- -- stomach -- -- -- --
-- -- -- -- -- -- only -- -- -- -- -- -- -- -- --
我用这个方法从那个搜索树的一个数组中搜索一个词,如果这个数组中的词存在于二叉搜索树上,它就会sysout它
public boolean contains(String d)
{
BSTNode p = root;
// Not contained if specified string is null
if (d == null)
return (false);
// OK if specified string equals our data
if ((p.data != null) && p.data.equals(d))
return (true);
// OK if contained in left tree
if ((p.left != null) && p.left.contains(d))
return (true);
// OK if contained in right tree
if ((p.right != null) && p.right.contains(d))
return (true);
// Otherwise, it's not OK
return (false);
}
包含 BSTNode 类中的方法
public boolean contains(String item) {
int comp = item.compareTo(data);
if(comp == 0) return true;
if(comp < 0 && left != null && left.contains(item)) return true;
if(comp > 0 && right != null && right.contains(item)) return true;
// no matching node was found
return false;
}
我就这样在main中使用它
for (int i = 0; i < len; i++) {
t = array[i];
if (btree.contains(array[i]) == true) {
System.out.println(t);
}
}
输出
was
in
it
was
the
only
the
the
was
in
in
the
the
the
was
only
the
我怎么能这样输出
- 仅:2
- 原为:4
- 它:1
- 在:3
- :7
...
所以我对代码的理解是它单独检查每个节点中的所有单词,而不是在所有节点中搜索一个单词然后移动到下一个单词,这样我得到了这个输出,如果我是,请纠正我错了。
希望有人能帮忙!
【问题讨论】: