C++遍历树非递归递归使用了标记位

//这不是最有效的方法,但使用了标记为容易理解,记下

/*
*   description:树的遍历示例,非递归版本
*               入栈顺序:
*               前序: 右子树   - 左子树   - 当前节点
*               中序: 右子树   - 当前节点 - 左子树
*               后序: 当前节点 - 右子树   - 左子树
*
*   writeby:    nick
*   date:       2012-10-22 23:56
*/
#include <iostream>
#include <stack>

using namespace std;

struct node
{
    int item;
    bool flag;
    node *l, *r;
    node(int n)
    {item=n; l=0; r=0; flag=false;}
};
typedef node *link;

//前序遍历
void pretraverse(link h, void visit(link))
{
    stack<link> s;
    s.push(h);
    while(!s.empty())
    {
        h = s.top();
        s.pop();
        visit( h );
        if (h->r != 0) s.push(h->r);
        if (h->l != 0) s.push(h->l);
    }
}

//中序遍历
void midtraverse(link h, void visit(link))
{
    stack<link> s;
    s.push(h);
    while(!s.empty())
    {
        h = s.top();
        s.pop();
        if(h->flag == true) {visit(h); continue;}

        if(h->r != 0 && h->r->flag == false) s.push(h->r);

        if(h->flag==false){ h->flag=true; s.push(h);}

        if(h->l != 0 && h->l->flag == false) s.push(h->l);
    }

}

//后序遍历
void posttraverse(link h, void visit(link))
{
    stack<link> s;
    s.push(h);
    while(!s.empty())
    {
        h = s.top();
        s.pop();
        if(h->flag == true) {visit(h); continue;}

        if(h->flag==false){ h->flag=true; s.push(h);}

        if(h->r != 0 && h->r->flag == false) s.push(h->r);

        if(h->l != 0 && h->l->flag == false) s.push(h->l);
    }
}

void visit(link p)
{
    cout << p->item << " ";
}

int main()
{
    link root = new node(4);
    root->l = new node(5);
    root->r = new node(6);
    root->l->l = new node(7);
    root->l->r = new node(8);

    cout << "先序遍历:";
    pretraverse(root, visit);

    cout << endl << "中序遍历:";
    midtraverse(root, visit);

    root->flag          = false;
    root->l->flag       = false;
    root->r->flag       = false;
    root->l->l->flag    = false;
    root->l->r->flag    = false;

    cout << endl << "后序遍历:";
    posttraverse(root, visit);

    return 0;
}
原文地址:https://www.cnblogs.com/wouldguan/p/2735511.html