2012-01-10 4 views
0

2つのバイナリツリーが等しいかどうかをチェックするメソッドを書いています。equals()メソッドはこのバイナリツリーで機能しますか?

これが正しいですか、それとも良い方法がありますか?

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

可能な複製であるのコーナーケースをカバーしていない[2つのバイナリツリーが等しいかどうかを判断し(http://stackoverflow.com/questions/1482822/determine-if-two-binary-trees-are-equal) –

答えて

2

次はあなたが探しているロジックにおそらく近いですが、完全にテストされていないと、このテキストフィールドに書かれていた:

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

現在のバージョンの欠陥がたくさんあります。上記

2

たちを聞かないでください - それは正しいだということを証明unit testsを書きます。

すべての種類のコーナーケースを含めるようにしてください。equals(null, null)は少なくともfalseを返すため、少なくとも1つのエラーがあると思います。

1
public boolean binaryTreeEquals(BinaryNode node1, BinaryNode node2) 
{ 
    if(node1 == node2 == null) 
     return true; 
    if(node1.element == node2.element && 
     binaryTreeEquals(node1.left, node1.right) && 
     binaryTreeEquals(node2.left, node2.right) 
     return true; 
    else 
     return false; 
} 

このコードは機能するはずです。 node1またはnode2がnullであるかどうかを確認してからfalseを返しますが、両方が等しい場合はチェックしています。

0
public boolean equals(BinaryNode root1, BinaryNode root2) { 
    if (root1 == null || root2 == null) { 
     return root1 == null && root2 == null; 
    } else { 
     return root1.data == root2.data 
     && equals2(root1.left, root2.left) 
     && equals2(root1.right, root2.right); 
    } 
} 

ソリューションの両方が1つのルートnullされ、他方はのNot null

関連する問題