C语言 – 数据结构 — 将二叉树的左右子树交换
#include<stdio.h>
#include<stdlib.h>
typedef struct Tree
{
int data;
struct Tree *lchild;
struct Tree *rchild;
}Tree, *BitTree;
BitTree CreateLink()
{
int data;
BitTree T;
scanf("%d", &data);
if (data == -1)
return NULL;
else
{
T = (BitTree)malloc(sizeof(Tree));
T->data = data;
printf("请输入%d的左子树: ", data);
T->lchild = CreateLink();
printf("请输入%d的右子树: ", data);
T->rchild = CreateLink();
return T;
}
}
BitTree InvertTree(BitTree B)
{
if (B == NULL)
return B;
BitTree left, right;
left = InvertTree(B->lchild);
right = InvertTree(B->rchild);
B->lchild = right;
B->rchild = left;
return B;
}
void Xianxu(BitTree T)
{
if (T == NULL)
return;
printf("%d ",T->data);
Xianxu(T->lchild);
Xianxu(T->rchild);
}
int main()
{
BitTree B;
printf("请输入二叉树的结点:\n");
B = CreateLink();
printf("交换前的二叉树为:\n");
Xianxu(B);
InvertTree(B);
printf("\n交换后二叉树为:\n");
Xianxu(B);
return 0;
}