zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    SpringBoot,来实现MySQL读写分离技术
    range范围
    tuple元组
    序列通用操作及可变序列通用操作
    list列表
    数据
    python基础知识
    charm写代码时添加快捷键
    2、添加到项目里 在⚙图标里选择Add Remote...charm初期设置(远程服务器)
    5、优化
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2735511.html
Copyright © 2011-2022 走看看