#include <stdlib.h>
#include <stdio.h>
#define STACK_INIT_SIZE 10
#define LIST_INIT_SIZE 100
#define STACKINCREMENT 10
#define DEBUG 1
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int TElemType,SElemType;
typedef int Status;
Status PrintElement(TElemType e);
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
typedef struct BiTNode{
TElemType data;
struct BiTNode
*lchild,*rchild;
}BiTNode,*BiTree;
Status InitStack(SqStack *S){ //初始化
S->base=(SElemType *)
malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S->base) exit(OVERFLOW);
S->top=S->base; //空栈
S->stacksize=STACK_INIT_SIZE;
return OK;
}
//获取栈顶元素,但栈顶指针不变:
Status GetTop(SqStack *S,SElemType *e){
if(S->top==S->base) return ERROR; //空栈
*e=*(S->top-1);
return OK;
}
Status Push(SqStack *S,SElemType e){ //入栈(压栈)
if(S->top-S->base>=S->stacksize){
S->base=(SElemType *)realloc(S->base,
(S->stacksize+STACKINCREMENT)
*sizeof(SElemType));
if(!S->base) exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
} //空间不够,重新分配空间
*S->top++=e;
return OK;
}
Status Pop(SqStack *S,SElemType *e){ //出栈
if(S->top==S->base) return ERROR;
*e=*--S->top;
printf("%c ", *e);
return OK;
}
Status StackEmpty(SqStack *S)
{
if(S->top==S->base) return 1;
return 0;
}
//先序遍历的递归形式
Status PreOrderTraverse(BiTree T,Status(Visit)(TElemType e))
{
if(T){ //T非空
printf("%c ", T->data);
if(T->data) //根
{
PreOrderTraverse(T->lchild,Visit);
PreOrderTraverse(T->rchild,Visit);
}
// if(PreOrderTraverse(T->lchild,Visit)) //左
// if(PreOrderTraverse(T->rchild,Visit))//右
return OK;
}else return ERROR; //T空
}
//先序输入
Status CreateBiTree(BiTree *T){
char ch;
scanf("%c",&ch);
if(ch=='#') *T=NULL;//空树
else{
if(!(*T=(BiTNode *)
malloc(sizeof(BiTNode))))
exit(OVERFLOW);
(*T)->data=ch;
CreateBiTree(&((*T)->lchild));
CreateBiTree(&((*T)->rchild));
}
return OK;
}
Status PrintElement(TElemType e)
{
printf("%c ",e);
return OK;
}
int main()
{
SqStack stack1;
BiTree tree1;
InitStack(&stack1);
CreateBiTree(&tree1);
PreOrderTraverse(tree1,PrintElement);
printf("\n");
return 0;
}
04-14
2042
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)