我有一个方法可以检查 BST 的节点是否等于另一棵树的另一个节点(在输入内部给出) - 无论结构如何。
这是我到目前为止所拥有的,但似乎我遗漏了一些东西。
public boolean sameValues(BSTInterface<T> other)
{
if(other == null && this != null)
return false;
else if(other.size() == 0 && this.size() == 0)
return true;
Object temp = null;
Object temp2 = null;
while(other.preorderIterator().hasNext() && this.preorderIterator().hasNext())
{
temp = other.preorderIterator().next();
temp2 = this.preorderIterator().next();
if(temp.equals(temp2))
return true;
else
return false;
}
return false;
}
有谁知道更好的方法吗? 谢谢。
最佳答案
由于多余的return false
,您的while()
循环在第一次迭代中终止。它应该看起来有点像:
while(other.preorderIterator().hasNext() && this.preorderIterator().hasNext())
{
temp = other.preorderIterator().next();
temp2 = this.preorderIterator().next();
if(temp.equals(temp2)) // same data found?
return true; // return success
// else // do not return! continue!
// return false;
}
return false;
}
关于java - BST 相等性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172688/