//头文件
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
typedef char TElemType;
typedef struct Node
{
TElemType data;
struct Node *Lchild,*Rchild;
}BiTreeNode,*BiTree;
#define STACKINCREAMENT 10
typedef BiTreeNode SElemType;
typedef struct stack
{
SElemType * base;
SElemType * tope;
int stacksize;
}SqStack;
void copy(BiTreeNode *S,BiTreeNode *T)
{
S->data=T->data;
S->Lchild=T->Lchild;
S->Rchild=T->Rchild;
}
void initStack(SqStack *S)
//栈的初始化操作
{
S->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
S->tope=S->base;
S->stacksize=STACK_INIT_SIZE;
}
void Push(SqStack *S,SElemType e)
//向栈内压入元素
{
if(S->tope-S->base>=S->stacksize)
{
S->base=(SElemType *)realloc(S->base,(S->stacksize+STACKINCREAMENT)*sizeof(SElemType));
S->tope=S->base+S->stacksize;
S->stacksize+=STACKINCREAMENT;
}
copy(S->tope,&e);
S->tope++;
}
SElemType Pop(SqStack *S)
//删除栈顶元素
{
SElemType e;
if(S->tope==S->base)
exit(0);
S->tope--;
copy(&e,S->tope);
return e;
}
int stackEmpty(SqStack *S)
{
if(S->tope==S->base)
return 1;
else return 0;
}
//CPP文件
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include "stack.h"
int count;
BiTreeNode *bt;
BiTreeNode *s[20];
SqStack S;
BiTreeNode *Creat_Bt()
//二叉树的构造。
{
int i,j;
TElemType x;
BiTreeNode *p;
BiTreeNode *root=(BiTreeNode *)malloc(sizeof(BiTreeNode));
printf(" i, x/n");
scanf("%d,%c",&i,&x);
while(i!=0&&x!='#')
{
p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
p->data=x;
p->Lchild=NULL;
p->Rchild=NULL;
s[i]=p;
if(i==1)
bt=p;
else
{
j=i/2;
if(i%2==0)
s[j]->Lchild=p;
else
s[j]->Rchild=p;
}
printf(" i, x/n");
scanf("%d,%c",&i,&x);
}
return bt;
}
BiTreeNode * LTraverse(BiTreeNode *bt)
{
BiTreeNode *temp=bt;
printf("%c",temp->data);
while(temp->Lchild!=NULL)
{
printf("%c",temp->Lchild->data);
if(temp->Rchild!=NULL)
{
Push(&S,*temp->Rchild);
}
temp=temp->Lchild;
}
return temp;
}
void Traverse (BiTreeNode *bt)
//非递归先序遍历二叉树
{
BiTreeNode *temp=bt;
temp=LTraverse(temp);
while(stackEmpty(&S)==0)
{
if(temp->Lchild==NULL)
{
*temp=Pop(&S);
}
temp=LTraverse(temp);
}
}
void main()
{
BiTreeNode *bt;
bt=Creat_Bt();
putchar('/n');
Traverse(bt);
getch();
}
输入样例
1,I
2,
3,s
4,l
5,e
6,d
7,n
8,o
9,v
10,
11,c
12,#