【資料結構】二叉樹的建立和遍歷(非遞迴)
阿新 • • 發佈:2018-11-08
該程式使用的是遞迴地建立方法,以及非遞迴的遍歷演算法
執行環境:Dev-C++
#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; } } bintnode *node; bintnode *createbintree() { char ch; bintnode *t; if((ch=getchar())=='#') { t=NULL; } else { t=(bintnode *)malloc(sizeof(bintnode)); t->data=ch; t->lchild=createbintree(); t->rchild=createbintree(); } return t; } //遞迴的前序遍歷,中序遍歷,後序遍歷 void preorder(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 inorder(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 postorder(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 () { node = createbintree(); preorder(node); return 0; }