我编写了一个方法来检查两个二叉树是否相等。
这是正确的还是有更好的方法?
public boolean equal(BinaryNode t1, BinaryNode t2){
if(t1==null || t2==null)
return false;
else if(t1.element != t2.element)
return false;
else if(equal(t1.left,t2.left))
return false;
else if(equal(t1.right,t2.right))
return false;
else
return true;
}
最佳答案
以下内容可能更接近您正在寻找的逻辑,但完全未经测试并写入此文本字段中:
if (t1==null && t2==null)
return true;
if (t1.element != t2.element)
return false;
return equal(t1.left, t2.left) && equal(t1.right, t2.right);
您当前的版本存在很多缺陷。
关于java - equals() 方法适用于此二叉树吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806497/