试编写算法交换以二叉链表做存储结构的二叉树中所有结点的左 右子树。

大学 子树,结点,算法 已帮助 人

试编写算法交换以二叉链表做存储结构的二叉树中所有结点的左、右子树。

热搜:二叉链表作为二叉树的存储结构,在具有n

答案解析

难度★★☆ 搜索
  • 算法由主函数和创建二叉树、交换二叉树左右子树、输出二叉树中序遍历序列四个函数组成。
       程序如下:
       #include<stdio.h>
       typedef struct node{
         int data;
         struct node*ichiid;
         struct node*rchiid;
       }BTNODE,*BINTREE;    /*定义二叉链表指针类型*/
       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)->Ichild));
          createbintree(&((*t)->rchiid));
         }
       }
       void exchange(BINTREE t)    /*交换二树左右子树*/
       }
         BINTREE p;
         if(t!=NULL)
         {
           exchange(t->ichild);
           exchange(t->rchild);
           p=t->ichild;
           t->lchild=t->rchild;
           t->rchild=p;
         }
       }
       void inorder(BINTREE t)    /*输出二叉树中序遍历序列*/
       {
         if(t)
         {
           inorder(t->ichild);
           printf("%d",t->data);
           inorder(t->rchild);
         }
       }
       main()    /*主函数*/
       {
         BINTREE t=NULL;
         printf("please input nodes of BINTREE:");
         createbintree(&t);
         printf("the inorder is:");
         inorder(t);    /*交换前,中序遍历*/
         exchange(t);
         printf("");
         printf("the inorder is:");
         inorder(t);    /*交换后,再中序遍历*/
       }
       程序执行输出情况为:
       please input nodes of BINTREE:
       1 2 4 0 0 5 0 0 3 0 6 0 0(回车)
       the inorder is:425136    /*交换前,中序遍历结果*/
       the inorder is:631524    /*交换二叉树中所有结点的左、右子树后,中序遍历结果*/