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/rightnull,看起来愚蠢,但它是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方法。

有两个问题可能会让你感到困惑:

  1. 在第一个实现中,检查"this==null"是多余的(在这个上下文中不能为null)。
  2. "this.left"one_answers";this.right"null检查也是多余的,因为它们是原语,并且永远不可能为null。

我认为应该是这样的:

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;
}

最新更新