【练习时间】2021/3/28
【题目名称】 交换二叉树的左右子树
输入数据:ABCD###E##F##
输出数据:A F B E C D
【代码分析】
void ExchangeTree(BiNode *bt)
{
if(bt==NULL)return;
else{
BiNode *temp=new BiNode;
temp=bt->lchild;
bt->lchild=bt->rchild;
bt->rchild=temp;
ExchangeTree(bt->lchild);
ExchangeTree(bt->rchild);
}
}
【源代码】
/*
ABCD###E##F##
A B C D E F
A F B E C D
*/
#include <iostream>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild;
BiNode *rchild;
};
BiNode *CreateTree()
{
char val;
cin>>val;
BiNode *bt=NULL;
bt=new BiNode;
if(val=='#')return NULL;
else{
bt->data=val;
bt->lchild=CreateTree();
bt->rchild=CreateTree();
}
return bt;
}
void ExchangeTree(BiNode *bt)
{
if(bt==NULL)return;
else{
BiNode *temp=new BiNode;
temp=bt->lchild;
bt->lchild=bt->rchild;
bt->rchild=temp;
ExchangeTree(bt->lchild);
ExchangeTree(bt->rchild);
}
}
void Pre(BiNode *bt)
{
if(bt==NULL)return;
else {
cout<<bt->data<<" ";
Pre(bt->lchild);
Pre(bt->rchild);
}
}
int main()
{
BiNode *root=CreateTree();
ExchangeTree(root);
Pre(root);
return 0;
}