非递归遍历二叉树

来源:互联网 发布:淘宝海外直邮可信吗 编辑:程序博客网 时间:2024/05/30 23:37
void preTraval(Node *head) {if (head == NULL)return;stack<Node *> st;st.push(head);while (!st.empty() ) {Node *t = st.top();st.pop();while (t) {//一边顺着左路走,一边遍历,并把右孩子放入栈中visit(t);if (t->right)st.push(t->right);t = t->left;}}}void inTraval(Node *head) {if (head == NULL)return;Node * t = head;stack<Node *> st;while (t !=NULL || !st.empty()) {while (t != NULL) {//顺着左路走,并把节点放入栈中st.push(t);t = t->left;}if (!st.empty()) {//走到左路的头之后,取栈中的节点,向右拐t = st.top();st.pop();visit(t);t = t->right;}}}


后序比较复杂

#define maxsize 100typedef enum{L,R} tagtype;typedef struct {    Bitree ptr;    tagtype tag;}stacknode;typedef struct{    stacknode Elem[maxsize];    int top;}SqStack;void PostOrderUnrec(Bitree t){    SqStack s;    stacknode x;    StackInit(s);    p=t;        do     {        while (p!=null)        //遍历左子树        {            x.ptr = p;             x.tag = L;         //标记为左子树,开始遍历其左子树            push(s,x);            p=p->lchild;        }            while (!StackEmpty(s) && s.Elem[s.top].tag==R)          {            x = pop(s);            p = x.ptr;            visite(p->data);   //tag为R,表示右子树访问完毕,故访问根结点               }                if (!StackEmpty(s))        {            s.Elem[s.top].tag =R;     //遍历右子树;左子树到头了,所以要开始遍历右子树            p=s.Elem[s.top].ptr->rchild;                }        }while (!StackEmpty(s));}//PostOrderUnrec 

struct Node {    int data;    Node *left;    Node *right;};struct PostNode {    Node *node;    int type;//0 左;1 右};void post(Node *root) {    stack<PostNode> st;    Node *t = root;    do     {        while(t!=NULL) {            PostNode pn;            pn->node = t;            pn.type = 0;            st.push(pn);            t = t->left;        }        while(!st.empty() && st.top().type == 1) {            cout<<st.top().node->data<<endl;            st.pop();        }        if (!st.empty()) {            st.top().type = 1;            t = st.top().node->right;        }    } while (!st.empty());}


原创粉丝点击