#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct node
{
char data;
struct node *leftChild;
struct node *rightChild;
}BiNode, *BiTree;
typedef struct {
BiNode data[MAXSIZE];
int top;
}SeqStack;
void InitStack(SeqStack *s) {
s->top = -1;
}
int IsEmpty(SeqStack *s) {
if (s->top == -1) {
return 1;
}
return 0;
}
int Push (SeqStack *s, BiNode *n) {
if (s->top == MAXSIZE-1) {
return 0;
}
else {
s->top++;
s->data[s->top] = *n;
return 1;
}
}
int Pop (SeqStack *s, BiNode *n) {
if (s->top == -1) {
return 0;
}
else {
*n = s->data[s->top];
s->top--;
return 1;
}
}
int GetTop(SeqStack *s, BiNode *n) {
if (s->top == -1) {
return 0;
}
else{
*n = s->data[s->top];
return 1;
}
}
void CreateBiTree(BiTree *root) {
char ch;
ch = getchar();
if (ch == '#') {
(*root) = NULL;
}
else {
(*root) = (BiTree)malloc(sizeof(BiNode));
(*root)->data = ch;
CreateBiTree(&((*root)->leftChild));
CreateBiTree(&((*root)->rightChild));
}
}
void PreOrder(BiTree root) {
SeqStack s;
BiTree p,q = NULL;
InitStack(&s);
p = root;
while (p!= NULL || !IsEmpty(&s)) {
while (p != NULL) {
printf("%c", p->data);
Push(&s, p);
q = p;
p = p->leftChild;
}
p=q;
if (!IsEmpty(&s)) {
Pop(&s, p);
p = p->rightChild;
}
}
}
int main(void) {
BiTree root;
CreateBiTree(&root);
PreOrder(root);
return 0;
}
输入
ABC##DE#G##F###
输出
ABCDEGF