比较两棵树的等于方法
只是另一个小问题。我还必须为 IntTree 类创建一个 equals 方法,该方法循环遍历两棵树并比较节点。如果树中的所有值都相等,则返回 true,否则返回 false。这是我到目前为止的代码:
private boolean equals(IntTreeNode node1, IntTreeNode node2){
if ((node1 != null) || (node2 != null)){
if (node1.equals(node2)){
equals(node1.left, node2.left);
equals(node1.right, node2.right);
return node1.equals(node2);
}
}
return false;
}
当我在驱动程序上调用此方法来比较两棵完全相同的树(blah1.equals(blah2))时,我得到错误。然而,当我打电话给 blah1.equals(blah1) 时,我明白了...... 我也不确定我的退货声明是否正确
just another slight problem. I must also create an equals method for my IntTree class which cycles through two tree's and compares the nodes. If all of the values in the tree are equal, then it returns true, otherwise it returns false. Here is the code I have so far:
private boolean equals(IntTreeNode node1, IntTreeNode node2){
if ((node1 != null) || (node2 != null)){
if (node1.equals(node2)){
equals(node1.left, node2.left);
equals(node1.right, node2.right);
return node1.equals(node2);
}
}
return false;
}
When I call this method on my Driver program to compare two tree's that are exactly alike (blah1.equals(blah2)), I get false. However, when I call blah1.equals(blah1) I get true...
I'm not sure if my return statement is correct either
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我冒昧地猜测您没有重写
IntTreeNode
的 equals 方法或者没有正确完成。我会这样做:
然后要比较两棵树,您可以调用 rootNode.equals(otherRootNode)
I'm going to hazard a guess that you haven't overridden the equals method of
IntTreeNode
or haven't done it correctly.I would do that something like this:
And then to compare the two trees you can just call
rootNode.equals(otherRootNode)
为什么要执行两个 equals 而不处理结果?
我会改变内在,如果只是
Why do you do two equals without handling the result?
I would change the inner if by just