二叉树的遍历--递归和非递归

来源:互联网 发布:柔术 知乎 编辑:程序博客网 时间:2024/06/06 01:41

PS:数据结构老师让写下二叉树的后序遍历的非递归算法,结果把所有的都写了一下

CODE

#include<iostream>#include<algorithm>#include<string.h>#include<stdio.h>#include<stdlib.h>#include<stack>using namespace std;typedef  struct Binode{    char data;    struct Binode *l, *r;};typedef struct node{    struct Binode *x;    bool flag;};char ls[150];int k;void creat(Binode *&T){    char c;     c = ls[k++];    if(c == '#')    {        return ;    }    else    {        T = new Binode;        T->l = NULL;        T->r = NULL;        T->data = c;        creat(T->l);        creat(T->r);    }}void pre(Binode *T)///先序递归--中左右{    if(T)    {        cout<<T->data;        pre(T->l);        pre(T->r);    }}void preBitree(Binode *T)///先序遍历非递归{    stack<node*> A;    Binode *p;    p = T;    while(p || !A.empty())    {        while(p)        {            cout<<p->data;            node *q;            q = new node;            q->x = p;            A.push(q);            p =p->l;        }        if(!A.empty())        {            node *q;            q = A.top();            A.pop();            if(q->x->r)            {                p = q->x->r;            }        }    }    cout<<endl;}void In(Binode *T)///中序递归--左中右{    if(T)    {        In(T->l);        cout<<T->data;        In(T->r);    }}void InBitree(Binode *T)///中序遍历非递归{    stack<node*> A;    Binode *p;    p  = T;    while(p || !A.empty())    {        while(p)        {             node *q;            q = new node;            q->x = p;            A.push(q);            p =p->l;        }        if(!A.empty())        {            node *q;            q = A.top();            A.pop();            cout<<q->x->data;            if(q->x->r)            {                p = q->x->r;            }        }    }    cout<<endl;}void post(Binode *T)///后序递归--左右中{    if(T)    {        post(T->l);        post(T->r);        printf("%c",T->data);    }}void postBitree(Binode *T)///后序非递归{     stack<node*> A;     Binode *p;     p = T;    while(p||!A.empty())    {        while(p){            node *q;            q = new node;            q->x = p;            q->flag = true;            A.push(q);            p =p->l;        }        if(!A.empty())        {        node *q;        q = A.top();        A.pop();        if(q->flag){                p = q->x->r;                if(p){                q->flag = false;                A.push(q);                }                else{                        cout<<q->x->data;                }        }        else{            cout<<q->x->data;        }    }    }    cout<<endl;}int main(){       while(~scanf("%s",ls))       {           k = 0;        Binode *root;        creat(root);        preBitree(root);       }    return 0;}/*abc##de#g##f###*/


0 0
原创粉丝点击