java - Java 简单二叉树检查等于
问题描述
我不知道为什么这个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”将立即引发 NullPointerException,而不会调用 equals 方法。
两个可能让你困惑的问题:
- 在第一个实现中,检查“this==null”是多余的(在这种情况下 this 不能为 null)。
- "this.left" 和 "this.right" 空检查也是多余的,因为它们是原语,并且永远不能为空。
在我看来,它应该是这样的:
public boolean equals(TreeNode other) {
if (other == null) {
return false;
}
// Different Values
if (this.val != other.val) {
return false;
}
if (this.left == null && other.left != null) {
return false;
}
if (this.left != null && !this.left.equals(other.left)) {
return false;
}
if (this.right == null && other.right != null) {
return false;
}
if (this.right != null && !this.right.equals(other.right)) {
return false;
}
return true;
}
推荐阅读
- json - 有没有办法我们可以在门户中查看失败的 arm 模板部署的输出?
- flutter - 有什么方法可以在颤振中使用 gojs 图表吗?
- python-tesseract - python tesseract 不能在 Heroku 上工作,我 pip 它,它安装了,但不工作?
- html - 如何创建具有正确角半径的线?
- reactjs - 如何让 VSCode 不检查目录中的其他 .ts 文件是否存在变量冲突?
- wordpress - 有没有办法防止键盘弹出în wrpdress
- c# - 仅在创建操作期间实体框架的 C# 验证注释
- php - 通过composer在laravel上安装包时出错
- java - Graal SDK 在应用程序运行但在单元测试中失败时工作
- regex - 为什么我的 apache 正则表达式 [a-f0-9] 只匹配数字?