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;
    }
  • 相关阅读:
    Android实战技巧之四十九:Usb通信之USB Host
    Netty in Action (七) 第三章节 Netty组件和设计
    打造敏捷的自组织团队
    Cocos2d-x移植到Android平台编译的两个文件Android.mk和Application.mk
    Codeforces Round #306 (Div. 2) (ABCE题解)
    事情非常重要却总不想開始怎么办
    <html>
    Android中Activity与Task相关的属性解析
    大话设计模式—策略模式
    android hander怎样避免内存泄露
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2735511.html
Copyright © 2011-2022 走看看