PTA7-1

题面

以二叉链表作为二叉树的存储结构,交换二叉树中每个结点的左孩子和右孩子。

输入格式

输入二叉树的先序序列。

提示:一棵二叉树的先序序列是一个字符串,若字符是‘#’,表示该二叉树是空树,否则该字符是相应结点的数据元素。

输出格式

输出有两行:

第一行是原二叉树的中序遍历序列;

第二行是交换后的二叉树的中序遍历序列。

输入样例

ABC##DE#G##F###

输出样例

CBEGDFA

AFDGEBC

AC代码

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

struct node //typedef node*tree;
{
    char x; // int x;
    node*lc,*rc; // node *lc;node *rc
};
int L,cnt;
string s;

void build(node* &T)
{
    if(s[cnt]=='#'||cnt==L) return;
    T=new node;
    T->x=s[cnt],T->lc=T->rc=NULL;
    cnt++,build(T->lc);
    cnt++,build(T->rc);
}

void swapp(node* &T)
{
    if(T->lc==NULL&&T->rc==NULL) return;
    swap(T->lc,T->rc); // node* temp;作为交换变量 不用也可以
    if(T->lc!=NULL) swapp(T->lc);
    if(T->rc!=NULL) swapp(T->rc);
}

void zh(node* T) //中序遍历
{
    if(T->lc!=NULL) zh(T->lc);
    printf("%c",T->x);
    if(T->rc!=NULL) zh(T->rc);
}

int main()
{
    cin>>s;
    L=s.length(),cnt=0;
    node* T=NULL; // = node *T=NULL = typedef node*tree,tree T=NULL;
    build(T),zh(T),cout<<endl;
    swapp(T),zh(T),cout<<endl;
    return 0;
}