比较两个二叉树



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

下面是将整数放入数组 的代码
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;
}
到目前为止(因为显而易见的原因),

只在树的长度不相等时才有效。我真的不知道代码出了什么问题,所以任何建议都会有所帮助。提前感谢

你好,你可以使用递归来比较两个二叉树的概念可能跟

 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],则需要跳出for循环。否则,结果将被设置为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)进行数组比较。这应该行得通。

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

最新更新