原部落格地址:http://blog.chinaunix.net/uid-20551990-id-371961.html
近期在看一些筆試面試題,發現很多題目涉及到樹,而其中遞迴演算法在解題中又顯得特別重要,所以轉了一篇文章用來查閱之用。
#include <stdio.h>#include <stdlib.h>struct tree{char data;struct tree *lchild;struct tree *rchild;};typedef struct tree * treptr;treptr build(treptr t)//先序建樹 {char c;c=getchar(); if(c=='#') {t=NULL;}else{t=(treptr)malloc(sizeof(struct tree));t->data=c;t->lchild=build(t->lchild);t->rchild=build(t->rchild);}return t;}#if 0 void postdorder_b(treptr root)//這是前序走訪遞迴實現{if (root!=NULL){printf("%c",root->data);postdorder(root->lchild);postdorder(root->rchild);}}void postdorder_m(treptr root)//這是中序遍曆遞迴實現{if (root!=NULL){postdorder(root->lchild);printf("%c",root->data);postdorder(root->rchild);}}void postdorder_l(treptr root)//這是後序遍曆遞迴實現{if (root!=NULL){postdorder(root->lchild);postdorder(root->rchild);printf("%c",root->data);}}#endifstruct stack{treptr *top,*base;};typedef struct stack *stackptr;void init (stackptr s)//初始化棧 {s->base=(treptr*)malloc(sizeof(treptr)*100);s->top=s->base;}void push(stackptr s,treptr t)//入棧 {*(s->top++)=t;}treptr pop(stackptr s)//彈出棧頂元素 {treptr t;t=*(--(s->top));return t;}treptr gettop(stackptr s)//取棧頂元素{treptr *l=s->top-1;return *(l);}void postorder_l(treptr t)//這是非遞迴後序實現{stackptr s=(stackptr)malloc(sizeof(struct stack));treptr temp=t;treptr p;treptr lastvist=NULL;init(s);p=t;while(p||s->top!=s->base){while(p){push(s,p);p=p->lchild;}temp=gettop(s);if(temp->rchild==NULL||temp->rchild==lastvist){putchar(temp->data);lastvist=pop(s);}elsep=temp->rchild;}}void postorder_m(treptr t)//這是非遞迴中序實現{stackptr s=(stackptr)malloc(sizeof(struct stack));treptr temp=t;treptr p;treptr lastvist=NULL;init(s);p=t;while(p||s->top!=s->base){while(p){push(s,p);p=p->lchild;}temp=pop(s);putchar(temp->data);p=temp->rchild;}}void postorder_b(treptr t)//這是非遞迴前序實現{stackptr s=(stackptr)malloc(sizeof(struct stack));treptr temp=t;treptr p;treptr lastvist=NULL;init(s);p=t;while(p||s->top!=s->base){while(p){putchar(p->data);push(s,p);p=p->lchild;}temp=pop(s);p=temp->rchild;}}int main(){treptr t=NULL;t=build(t);//postdorder(t);printf("\n非遞迴前序走訪\n");postorder_b(t);printf("\n非遞迴中序遍曆\n");postorder_m(t);printf("\n非遞迴後序遍曆\n");postorder_l(t);printf("\n");return 0;}