先序遍历遇到的问题,高手进
程序代码:
#include<stdio.h> #include<stdlib.h> //包括malloc()和realloc()函数的头文件 #include<math.h> //包括pow()函数的头文件 #define Max_stack_size 20 #define Addersize 10 typedef struct BiTNode { char data; struct BiTNode *lchild; struct BiTNode *rchild; }BiTNode,*BiTree; typedef struct{ BiTNode *base; BiTNode *top; int stacksize; }sqStack; BiTree CreateBiTree(BiTree T) { char ch; fflush(stdin); if((ch=getchar())=='#') { T=NULL; } else { T=(BiTNode *)malloc(sizeof(BiTNode)); if(!T) exit(0); T->data=ch; T->lchild=CreateBiTree(T->lchild); T->rchild=CreateBiTree(T->rchild); } return T; } void initStack (sqStack *s) { //初始化一个空栈 s->base=(BiTNode *)malloc(Max_stack_size*sizeof(BiTNode)); if(!s->base) exit(0); s->top=s->base; s->stacksize=Max_stack_size; } void pushStack(sqStack *s,BiTNode e) { //入栈操作 if(s->top-s->base>=s->stacksize) { printf("栈已满,追加空间"); s->base=(BiTNode *)realloc(s->base,(s->stacksize+Addersize)*sizeof(BiTNode)); if(!s->base) exit(0); s->top=s->base+s->stacksize; s->stacksize=s->stacksize+Addersize; } *(s->top++)=e; } void popStack(sqStack *s,BiTNode *e) { //出栈操作 if(s->top==s->base) exit(0); *e=*--s->top; } int stackempty(sqStack *S) { if(S->top==S->base) return 1; else return 0; } void Preorder(BiTNode *T) { sqStack S; BiTNode *p; initStack(&S); p=T; while(p||!(stackempty(&S))) { if(p) { printf("%c ",p->data); pushStack(&S,*p); p=p->lchild; } else { popStack(&S,p); p=p->rchild; } } } int main() { BiTNode *T; T=CreateBiTree(T); Preorder(T); }
假如输入34##5## 结果只有3和4 没有5
为什么??