pintia7-2 交换二叉树每个结点的左孩子和右孩子
include<stdio.h>
include<string.h>
include
using namespace std;
struct node //typedef nodetree;
{
char x; // int x;
nodelc,*rc; // node *lc;node *rc
};
int L,cnt;
string s;
void build(node* &T)
{
if(s[cnt]'#'||cntL) 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->lcNULL&&T->rcNULL) 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 nodetree,tree T=NULL;
build(T),zh(T),cout<<endl;
swapp(T),zh(T),cout<<endl;
return 0;
}
浙公网安备 33010602011771号