用栈实现
#include <stdio.h>
#include <stdlib.h>
typedef struct TREE {
char data;
struct TREE* Lchild;
struct TREE* Rchild;
}TREE,*PTREE;
typedef struct STACK {
struct TREE* data;
struct STACK* next;
}STACK,*PSTACK;
PSTACK init() {
PSTACK S = (PSTACK)malloc(sizeof(STACK));
S->data = NULL;
S->next = NULL;
return S;
}
int isempty(PSTACK S) {
if (S->next == NULL) {
return 1;
}
else
{
return 0;
}
}
void push(PSTACK S, PTREE T) {
PSTACK NEWNODE = (PSTACK)malloc(sizeof(STACK));
NEWNODE->data = T;
NEWNODE->next = S->next;
S->next = NEWNODE;
}
PSTACK pop(PSTACK S) {
if (isempty(S)) {
return;
}
PSTACK temp = S->next;
S->next = temp->next;
return temp;
}
void create(TREE** T) {
char data;
scanf("%c", &data);
getchar();
if (data != '#') {
*T = (PTREE)malloc(sizeof(TREE));
(*T)->data = data;
create(&(*T)->Lchild);
create(&(*T)->Rchild);
}
else
{
*T = NULL;
}
}
void preorder(PSTACK S,PTREE T) {
PTREE node = T;
while (node || !isempty(S)) {
if (node) {
printf("%c", node->data);
push(S, node);
node = node->Lchild;
}
else
{
node = pop(S)->data;
node = node->Rchild;
}
}
}
void inorder(PSTACK S, PTREE T) {
PTREE node = T;
while (node || !isempty(S)) {
if (node) {
push(S, node);
node = node->Lchild;
}
else
{
node = pop(S)->data;
printf("%c", node->data);
node = node->Rchild;
}
}
}
int main() {
PTREE T;
create(&T);
PSTACK S = init();
preorder(S, T);
printf("\n");
inorder(S, T);
return 0;
}