题目意思是根据它删除的节点构建出一棵树,然后先序遍历.用指针构建很简洁,但是指针没学好,各种bug,一下午就写了一棵树.代码中的Freefun()函数至今没调试对,求指教!!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <malloc.h>
using namespace std;
const int maxn = 100;
typedef struct tnode{
char data;
tnode *l;
tnode *r;
}*Node;
char s[maxn][maxn];
Node Head;
void CreatTree( Node &H, char v){
if(H == NULL){
H = (tnode*)malloc(sizeof(tnode));
H->data = v;
H->l = NULL;
H->r = NULL;
}
else if(v <= H->data) CreatTree( H->l, v);
else CreatTree( H->r, v);
}
void VisitTree( Node &H){
if(H != NULL) printf("%c",H->data);
if(H->l != NULL) VisitTree(H->l);
if(H->r != NULL) VisitTree(H->r);
}
void Freefun( Node &H){
if(H != NULL) free(H);
if(H->l != NULL) Freefun(H->l);
if(H->r != NULL) Freefun(H->r);
}
int main(){
int cnt;
while(true){
Head = NULL;
for(int i = 0; ;++i){
scanf("%s",s[i]);
if(strcmp(s[i],"*") == 0 || strcmp(s[i],"$") == 0){
cnt = i;
break;
}
}
for(int i = cnt - 1; i >= 0; --i)
for(int j = 0; s[i][j] != '\0'; ++j)
CreatTree(Head,s[i][j]);
VisitTree(Head);
putchar('\n');
//Freefun(Head);
if(strcmp(s[cnt],"$") == 0) break;
}
return 0;
}