问答题 试编写算法判断两棵二叉树是否等价。如果T1和T2都是空的二叉树或者T1和T2的根结点的值相同,并且T1的左子树与T2的左子树是等价的,T1的右子树与T2的右子树是等价的,则称二叉树T1和T2是等价的。
【正确答案】算法由主函数和创建二叉树、判断两棵二叉树是否等价三个函数组成。
   程序如下:
    #include<stdio.h>
   typedef struct node
   {
     int data;
     struct node*lchild;
     struct node *rchild;
   }BTNODE.*BINTREE;    /*定义二叉链表指针类型*/
   in flag=0;
   void createbintree(BINTREE*t)  /*输入二叉树的先序遍历序列,创建二叉树*/
   {
     int a;
     scanf("/%d",&a);
     if(a==0)
     *t=NULL;
   else
   {
     *t=(BTNODE*)malloc(sizeof(BTNODE));
   (*t)->data=a;
   Createbintree (&*(t)->lchild;
   createbintree(&(*t)->rchild);
  }
 }
 void equal(BINTREE t1,BINTREE t2)/*判断二叉树t1和t2是否等价,flag=0等价,
                                    flag=1不等价,*/
 {
   if(t1&&t2)    /*t1和t2都不为空*/
   {
   if(t1->data==t2->data)
   {
     equal(t1->ichild,t2->ichild);
     equal(t1->rchild,t2->rchild);
   }
   else
     flag=1;
 }
 else
   if((t1&&!t2)‖(!t1&&t2))
   flag=1:
 }
 main()    /*主函数*/
 {
   BINTREE t1=NULL;
   BINTREE t2=NULL;
   printf("\nplease input nodes of T1 BINTREE:\n");
   createbintree(&t1);
   printf("\nplease input nodes of T2 BINTREE:\n");
   createbintree(&t2);
   equal(t1,t2);
   if(flag==0)
     printf("two trees are equal!");
   else
     printf("two trees are not equal!");
  }
   程序第一次执行输出情况为:
   please input nodes of T1 BINTREE:
   1 0 0(回车)
   please input nodes of T2 BINTREE:
   1 0 0(回车)
   two trees are equal!
   程序第二次执行输出情况为:
   please input nodes of T1 BINTREE:
   1 0 0(回车)
   please input nodes of T2 BINTREE:
   1 2 0 0 0(回车)
   two trees are not equal !
【答案解析】