王道数据结构p149——9
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode{
char data;
struct treenode *lchild,*rchild;
}treenode,*tree;
//ABD##E##C## //ABD##E##CF##G##
void create(tree &t);
void swap(tree &t);
void printtree(tree t);
int main(){
tree T;
//stack s;
create(T);
swap(T);
printtree(T);
return 0;
}
void swap(tree &t){
if(t){
if(t->lchild || t->rchild){
treenode *p;
p = t->lchild;
t->lchild = t->rchild;
t->rchild = p;
}
swap(t->lchild);
swap(t->rchild);
}
}
void printtree(tree t){
if(t){
printf("%c ",t->data);
printtree(t->lchild);
printtree(t->rchild);
}
}
void create(tree &t){
char c;
c = getchar();
if(c == '#') t = NULL;
else{
t = (treenode*)malloc(sizeof(treenode));
t->data = c;
t->lchild = NULL;
t->rchild = NULL;
create(t->lchild);
create(t->rchild);
}
}
注:这到题就是基于上一题进行部分修改即可