• 二叉树的非递归遍历


    #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;
    }
  • 相关阅读:
    PCI总线原理(二)
    smbus协议
    PCI总线原理(一)
    计算机术语中关于 Assert 和Deassert 词汇意思
    用安全存储器实现FPGA的身份识别及防拷贝
    主板结构
    qt 雅黑字体
    PCIExpress总线简介
    PHY管理接口(MDIO)
    PCI总线原理(三)
  • 原文地址:https://www.cnblogs.com/oleolema/p/9043062.html
Copyright © 2020-2023  润新知