以二叉链表作为二叉树的存储结构,交换二叉树中每个结点的左孩子和右孩子。
输入格式:
输入二叉树的先序序列。
提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。
输出格式:
输出有两行:
第一行是原二叉树的中序遍历序列;
第二行是交换后的二叉树的中序遍历序列。
输入样例:
ABC##DE#G##F###
输出样例:
CBEGDFA
AFDGEBC
是期中考试题喵~
虽然不难但是我在create的时候卡了一会,有点懵逼,可能没绕过弯来……还是太菜了
直接贴代码,一点零五了,去睡觉
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<queue>
#include<cstring>
using namespace std;
typedef struct bitree{
char data;
struct bitree *lc;
struct bitree *rc;
}bitree;
bitree *create()
{
bitree *t=(bitree*)malloc(sizeof(bitree));
char c;
scanf("%c",&c);
if(c!='#'){
t->data=c;
t->lc=create();
t->rc=create();
}
else return NULL;
return t;
}
void swap_t(bitree *t)
{
bitree *left,*right;
left=t->lc;
right=t->rc;
t->lc=right;
t->rc=left;
if(t->lc)swap_t(t->lc);
if(t->rc)swap_t(t->rc);
}
void mid_print(bitree *t)
{
if(t->lc)mid_print(t->lc);
cout<<t->data;
if(t->rc)mid_print(t->rc);
}
int main(){
bitree *T;
T=create();
mid_print(T);
cout<<endl;
swap_t(T);
mid_print(T);
return 0;
}