1、编写递归算法,将二叉树中所有结点的左右子树相互交换。(用C编程)
收起
知与谁同
2018-07-19 18:39:53
2525
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