2011-12-07 86 views
2

基本上这下面的代码将检查两个不同的二叉树是否具有相同的整数成员。我应该这样做的方式是将树中的整数存储到数组,然后比较数组。比较两个二叉树

这里是把整数数组

private static int toarray (btNode t, int[] a, int i) 
{ 
    int num_nodes = 0; 
    if (t != null) 
    { 
     num_nodes = toarray (t.left , a , i); 
     a [num_nodes + i] = t.info; 
     num_nodes = num_nodes + i + toarray (t.right,a,num_nodes + i + 1); 
    } 
    return num_nodes; 
} 

下面的代码是检查两棵树是否相等的代码

public boolean equals(Intcoll6 obj) 
{ 
    boolean result = true; 
    if (how_many == obj.how_many) 
    { 
     int[]a = new int [how_many]; 
     int[]b = new int [obj.how_many]; 


     toarray (c,a,0); 
     toarray (obj.c,b,0); 


     for (int j = 0; j < how_many; j++) 
     { 

      if (a[j] == (b[j])) 
      { 
       result = true; 
      } 
      else 
       result = false; 
     } 
    } 
    else 
    { 
     result = false; 
    } 
    return result; 
} 

至今(出于显而易见的原因),它只有在树的长度不相等时才有效。我无法弄清楚代码有什么问题,所以任何建议都会有帮助。在此先感谢

回答

4

嗨,你可以使用递归比较两个binaryTrees概念可能喜欢跟着

int compareTree(tree1, tree2) { 
    //if both are empty the return true 
if (tree1==NULL && tree2==NULL) return(true); 

// if both non-empty then compare them 
else if (tree1!=NULL && tree2!=NULL) { 
return 
    //compare values and recursive call the function for next data && 
    //compareTree(left node of tree1,left node of tree2) && 
    //compareTree(right node of tree1,right node of tree2) 
    ; 
} 
// if one empty, and other not then return false 
else return(false); 
} 
+0

好的,让我试试看 – GeneralPringles

1

你需要打出来的for循环,如果你遇到一个[J]!= B [ J]。否则结果将被设置为false,但可能会在下一个元素上设置为true。

例如,假设您正在比较数组[1,2,3,4,5]和[1,2,-7,4,5]。循环的前两个迭代将设置result = true;第三个将设置结果= false;那么第四个和第五个将再次设置result = true。到你回来的时候,你的结果=真,这是错误的。

也许更好的方法是完全删除result = true语句,因为它是多余的:您已经将结果初始化为true。相反,您可以只有:

if (a[j] != (b[j])) 
{ 
    result = false; 
    break; 
} 
0

尝试使用Arrays.deepEquals(a1, a2)进行数组比较。它应该工作。

然而,您将需要创建一个Integer数组而不是int,因为此函数在Object []上工作。