镜像二叉树,输入一个二叉树,输出二叉树的镜像。
分析:这道题不是很难,通过递归就可以实现。具体看代码
#include <stdio.h>
#include <stdlib.h>
typedef struct d{
int data;
struct d *left;
struct d *right;
}tree;
tree *buildt(int a[],int &n)
{
int num=a[n++];
if(num==NULL)
{
return NULL;
}
tree *s=(tree *)malloc(sizeof(tree));
s->data=num;
s->left=buildt(a,n);
s->right=buildt(a,n);
return s;
}
void Mirror(tree *t)
{
if(t!=NULL)
{
tree *tl,*tr;
tl=t->left;
tr=t->right;
t->left=tr;
t->right=tl;
Mirror(t->left);
Mirror(t->right);
}else
{
return;
}
}
tree *Ms(tree *t)
{
tree *ret=t;
Mirror(t);
return ret;
}
void Pre(tree *t)
{
if(t!=NULL)
{
printf("%d->",t->data);
Pre(t->left);
Pre(t->right);
}
}
void Mid(tree *t)
{
if(t!=NULL)
{
Mid(t->left);
printf("%d->",t->data);
Mid(t->right);
}
}
int main()
{
int a[]={1,2,4,0,0,5,0,0,3,6,0,0,7,0,0};
int n=0;
tree *t=buildt(a,n);
printf("镜像前前序遍历:");
Pre(t);
printf("\n镜像前中序遍历");
Mid(t);
tree *t2=Ms(t);
printf("\n镜像后前序遍历:");
Pre(t2);
printf("\n镜像后中序遍历:");
Mid(t2);
}