写的不标准,凑活着。( ̄o ̄) . z Z
bitree.h #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int Status; //定义二叉树 typedef char TElemType; typedef struct BiTNode{ TElemType data; struct BiTNode *lchild, *rchild; }BiTNode,*BiTree; //定义栈 typedef BiTree SElemType; typedef struct{ SElemType * base; SElemType * top; int stacksize; }SqStack;
stack.c #include "bitree.h" ///////////////////////初始化栈 Status InitStack_Sq(SqStack * S){ S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!S) exit(OVERFLOW); S->top = S->base; S->stacksize = STACK_INIT_SIZE; 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->top + 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; return OK; } ///////////////////////栈是否为空 Status EmptyStack(SqStack * S){ if(S->top == S->base) return OK; }
bitree.c #include <stdio.h> #include <stdlib.h> #include "stack.c" //创建二叉树,先序 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 PreOrderTraverse(BiTree T) { if(T){ printf("%c ",T->data); PreOrderTraverse(T->lchild); PreOrderTraverse(T->rchild); }else return OK; } //中序遍历 Status InOrderTraverse(BiTree T) { if(T) { InOrderTraverse(T->lchild); printf("%c ",T->data); InOrderTraverse(T->rchild); }else return OK; } //后序遍历 Status PostOrderTraverse(BiTree T) { if(T){ PostOrderTraverse(T->lchild); PostOrderTraverse(T->rchild); printf("%c ",T->data); }else return OK; } /* * 中序遍历 非递归 */ Status InOrderTraverse_(BiTree T){ SqStack S; BiTree p; InitStack_Sq(&S); p=T; while(p || EmptyStack(&S) != OK){ if(p){ Push(&S,p); p=p->lchild; }else{ Pop(&S, &p); printf("%c ",p->data); p=p->rchild; } } return OK; } //主函数 int main(){ BiTree T; printf("输入结点值 : "); //ABC DE G F if(CreateBiTree(&T)) printf("构建成功! "); printf("Pre先序遍历 "); PreOrderTraverse(T); printf(" In中序遍历 "); InOrderTraverse(T); printf(" Post后序遍历 "); PostOrderTraverse(T); printf(" In_中序遍历非递归 "); InOrderTraverse_(T); system("pause"); return 0; }