二叉樹的非遞迴前序,中序,後序遍曆演算法

來源:互聯網
上載者:User

原部落格地址: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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.