开发者社区> 问答> 正文

1、编写递归算法,将二叉树中所有结点的左右子树相互交换。(用C编程)

要快啊,我是上机作业,各位高手,运行出来我加分!

展开
收起
知与谁同 2018-07-19 18:39:53 2481 0
2 条回答
写回答
取消 提交回答
  • void biTreeChange(biTree tr)
    {
    if (tr == NULL) return;
    pNode pn = tr->left;
    tr->left = tr->right;
    tr->right = pn;
    biTreeChange(tr->left);
    biTreeChange(tr->right);
    }
    2019-07-17 22:54:40
    赞同 展开评论 打赏
  • 胜天半子
    #include<stdio.h>
    #include<malloc.h>
    typedef struct binode{
    int data;
    struct binode *lchild,*rchild;
    }binode,*bitree;
    typedef struct{
    bitree elem[100];
    int top;
    }stack;
    bitree creat_bt(){ //按扩展前序建二叉树
    bitree t;int x;
    scanf("%d",&x);
    if (x==0) t=NULL;
    else { t=(bitree)malloc(sizeof(binode));
    t->data=x;
    t->lchild=creat_bt();
    t->rchild=creat_bt();
    }
    return t;
    }
    void exchange(bitree t) //左、右子树交换
    {bitree p;
    if(t!=NULL)
    { p=t->lchild;t->lchild=t->rchild;
    t->rchild=p;
    exchange(t->lchild);
    exchange(t->rchild);
    }
    }
    void inorder(bitree bt) //递归的中序遍历
    { if (bt){
    inorder(bt->lchild);
    printf("% d",bt->data);
    inorder(bt->rchild);
    }
    }
    main()
    {bitree root;
    printf("\n");
    printf("建二叉树,输入元素:");
    root=creat_bt(); /*create tree of useing preorder*/
    printf("交换前的中序序列是:");
    inorder(root);
    exchange(root);
    printf("\n交换后的中序序列是:");
    inorder(root);
    printf("\n");
    }
    2019-07-17 22:54:40
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
数据+算法定义新世界 立即下载
袋鼠云基于实时计算的反黄牛算法 立即下载
Alink:基于Apache Flink的算法平台 立即下载