Java 两种二叉树的比较

Java 两种二叉树的比较,java,Java,基本上,下面的代码将检查两个不同的二叉树是否具有相同的整数成员。我应该这样做的方法是将整数从树存储到数组,然后比较数组 下面是将整数放入数组的代码 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]

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

下面是将整数放入数组的代码

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;
}
public boolean equals(Intcoll6 obj)
{
布尔结果=真;
if(how_many==obj.how_many)
{
int[]a=新的int[数量];
int[]b=新的int[obj.多少];
toarray(c,a,0);
toarray(对象c、b、0);
对于(int j=0;j

到目前为止(出于明显的原因),它只在树的长度不相等时起作用。我真的不知道代码出了什么问题,所以任何建议都会有帮助。提前感谢

您好,您可以使用递归来比较两个二叉树,这一概念可能如下所示

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

如果遇到a[j]!=b[j]。否则,结果将设置为false,但在下一个元素上可能会设置回true

例如,假设您正在比较数组[1,2,3,4,5]和[1,2,-7,4,5]。循环的前两次迭代将设置result=true;第三个将设置result=false;然后第四个和第五个将再次设置result=true。当您返回时,您将得到result=true,这是错误的

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

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

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

但是,您需要创建一个整数数组而不是int,因为此函数适用于对象[]