二叉樹遞迴與非遞迴的(前,中,後)遍歷
阿新 • • 發佈:2018-12-20
#include<stdio.h> #include<stdlib.h> typedef struct node { char data; struct node *lchild,*rchild; }bintnode; typedef struct stack { bintnode *data[100]; int tag[100]; int top; }seqstack; void push(seqstack *s,bintnode *t) { s->data[s->top]=t; s->top++; } bintnode *pop(seqstack *s) { if(s->top!=0) { s->top--; return (s->data[s->top]); } else { return NULL; } } int d=0; bintnode *createtree()/*按照前序遍歷建立一個二叉樹*/ { char ch; bintnode *t; if((ch=getchar())==' ') t=NULL; else { t=(bintnode*)malloc(sizeof(bintnode)); t->data=ch; t->lchild=createtree(); t->rchild=createtree(); } return t; } void compute(bintnode *t)/*前序遍歷計算葉子節點個數*/ { if(t) { if(t->lchild==NULL&&t->rchild==NULL) d++; compute(t->lchild); compute(t->rchild); } } void ino1(bintnode *t)/*中序遍歷*/ { if(t) { ino1(t->lchild); printf("%c ",t->data); ino1(t->rchild); } } void pos1(bintnode *t) { if(t) { pos1(t->lchild); pos1(t->rchild); printf("%c ",t->data); } } void pre1(bintnode *t) { if(t) { printf("%c ",t->data); pre1(t->lchild); pre1(t->rchild); } } //-------------------------------------------------- void pre2(bintnode *t)//前序遍歷 { seqstack s; s.top=0; while((t)||(s.top)!=0) { if(t) { printf("%c ",t->data); push(&s,t); t=t->lchild; } else { t=pop(&s); t=t->rchild; } } } void ino2(bintnode *t)//中序遍歷 { seqstack s; s.top=0; while((t!=NULL)||(s.top!=0)) { if(t) { push(&s,t); t=t->lchild; } else { t=pop(&s); printf("%c ",t->data); t=t->rchild; } } } void pos2(bintnode *t)//後序遍歷 { seqstack s; s.top=0; while((t)||(s.top!=0)) { if(t) { s.data[s.top]=t; s.tag[s.top]=0; s.top++; t=t->lchild; } else if(s.tag[s.top-1]==1) { s.top--; t=s.data[s.top]; printf("%c ",t->data); t=NULL; } else { t=s.data[s.top-1]; s.tag[s.top-1]=1; t=t->rchild; } } } int main() { bintnode *t; t=(bintnode*)malloc(sizeof(bintnode)); printf("請建立二叉樹:"); t=createtree(); printf("\n葉子節點個數:"); compute(t); printf("%d",d); printf("\n------------------------------\n"); printf("\n遞迴"); printf("\n前序遍歷:"); pre1(t); printf("\n中序遍歷:"); ino1(t); printf("\n後序遍歷:"); pos1(t); printf("\n-----------------------------\n"); printf("非遞迴"); printf("\n前序遍歷:"); pre2(t); printf("\n中序遍歷:"); ino2(t); printf("\n後序遍歷:"); pos2(t); printf("\n"); return 0; }