测试用例如图:
#include <stdio.h>
#include <stdlib.h>
#define TREE "+*E*D/CAB"
typedef int dt;
typedef struct NODE {
dt data;
struct NODE *lp;
struct NODE *rp;
} Node, *Nodep;
void first(Nodep ptr) {
if (ptr) {
printf("%c", ptr->data);
first(ptr->lp);
first(ptr->rp);
}
}
void mid(Nodep ptr) {
if (ptr) {
mid(ptr->lp);
printf("%c",ptr->data);
mid(ptr->rp);
}
}
void last(Nodep ptr) {
if (ptr) {
last(ptr->lp);
last(ptr->rp);
printf("%c", ptr->data);
}
}
int main() {
Nodep root = NULL;
Nodep tnode = (Nodep)malloc(sizeof(Node));
Nodep pl = NULL;
Nodep pr = NULL;
char s[] = TREE;
//建立二叉树
root = tnode;
tnode->data = s[0];
tnode->lp = NULL;
tnode->rp = NULL;
char *p = s + 1;
while(*p) {
//printf("%c", *p++);
pl = (Nodep)malloc(sizeof(Node));
pl->data = *p++;
pl->lp = NULL;
pl->rp = NULL;
pr = (Nodep)malloc(sizeof(Node));
pr->data = *p++;
pr->lp = NULL;
pr->rp = NULL;
tnode->lp = pl;
tnode->rp = pr;
tnode = tnode->lp;
}
//test
puts("Middle:");
mid(root);
puts("");
puts("First:");
first(root);
puts("");
puts("Last:");
last(root);
puts("");
puts("");
return 0;
}