【发布时间】:2021-02-03 02:27:44
【问题描述】:
我不明白为什么这个equals 函数不起作用:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
public boolean equals(TreeNode other) {
if (this == null && other == null) {
return true;
} else if (this == null || other == null) {
return false;
} else {
return this.val == other.val
&& this.left.equals(other.left)
&& this.right.equals(other.right);
}
}
}
似乎主要问题是我无法比较 null TreeNode,但在设置中我已经指出了如何处理 null?
TreeNode a = new TreeNode(5);
TreeNode b = new TreeNode(5);
System.out.println(a.equals(b)); // >>> NullPointerException
上面的比较是从非空开始的,但最终当分支到空左或空右时它会命中空。一种工作方法是将上述相同的方法提取到静态方法中:
public static boolean isEqual(TreeNode self, TreeNode other) {
if (self == null && other == null) {
return true;
} else if (self == null || other == null) {
return false;
} else {
return self.val == other.val
&& isEqual(self.left, other.left)
&& isEqual(self.right, other.right);
}
}
这样可以正常工作:
TreeNode a = new TreeNode(5);
TreeNode b = new TreeNode(5);
System.out.println(TreeNode.isEqual(a, b)); // >>> true
下面也可以,避免this.left/right成为null,看起来很愚蠢,但它是java
public boolean equals(TreeNode other) {
if (this.left == null && other.left == null && this.right == null && other.right == null) {
return this.val == other.val;
} else if (this.left != null && other.left != null && this.right != null && other.right != null) {
return this.val == other.val && this.left.equals(other.left) && this.right.equals(other.right);
} else if (this.left != null && other.left != null && this.right == null && other.right == null) {
return this.val == other.val && this.left.equals(other.left);
} else if (this.left == null && other.left == null && this.right != null && other.right != null) {
return this.val == other.val && this.right.equals(other.right);
} else {
return false;
}
}
【问题讨论】:
-
a.equals(....),当您调用它时,a到底是什么?提示:它不是不为空的东西。 -
a是TreeNode即null? -
对,在
null上调用方法会导致? -
在 python 中,确切的代码可以正常运行。你能建议我应该如何避免这种情况吗?
-
是的,因为它是
equals(Object)。 That equals 方法是在 Set 和其他容器类中使用的方法。因此,代码有点误导/混淆。这就是我想要表达的全部内容。
标签: java data-structures binary-tree equals