二叉树的非递归遍历

#include"iostream"
#include"stack"
using namespace std;
typedef char element;
class Tree{
private:
    element data;
    Tree *right,*left;
public:
    Tree(element data = 0){
        this->data = data;
        right = NULL;
        left = NULL;
    }

    void cinCreate(Tree* &t){
        element data;
        cin>>data;
        if(data != '#'){
            t = new Tree(data);
            cinCreate(t->left);
            cinCreate(t->right);
        }
    }
    //非递归的先序遍历
    void showux(){
        stack<Tree*> s;
        Tree *t = this;
        while(t || !s.empty()){
            while(t){
                s.push(t);
                cout<<t->data<<ends;
                t = t->left;
            }
            t = s.top();
            s.pop();
            t = t->right;
        }
    }
    //非递归的中序遍历
    void showuz(){
        stack<Tree*> s;
        Tree *t = this;
        while(t || !s.empty()){
            while(t){
                s.push(t);
                t = t->left;
            }
            t = s.top();
            s.pop();
            cout<<t->data<<ends;
            t = t->right;
        }
    }
    //后序遍历比较复杂,此处不写



    //更方便的非递归遍历(前中后)
    void showux1(){
        stack<Tree*> s;        //树结点
        stack<int> v;        //标志位(标记根节点 与 孩子结点,是根结点就输出)
        Tree *t = this;int v1;
        s.push(t);v.push(0);
        while(!s.empty()){
            t = s.top();v1 = v.top();
            s.pop();v.pop();
            if(v1){
                cout<<t->data<<ends;
            }
            else if(t){
                //只需调整位置就可完成 前中后序遍历
                s.push(t->right);v.push(0);
                s.push(t);v.push(1);
                s.push(t->left);v.push(0);
            }
        }
    }
    //递归的先序遍历
    void showx(){
        if(this){
            cout<<data<<ends;
            left->showx();
            right->showx();
        }
    }

};
/*
124##5##36##7##
*/
int main(){
    Tree *t;
    t->cinCreate(t);
    t->showx();
    cout<<endl;
    t->showux1();
    return 0;
}
原文地址:https://www.cnblogs.com/oleolema/p/9043062.html