zoukankan      html  css  js  c++  java
  • 前序中序后序遍历非递归实现

    #include<iostream>
    #include<vector>
    #include<stack>
    #include<string>
    #include<algorithm>
    #include<numeric>
    using namespace std;
    
    class node{
    public:
        int val;
        node* left;
        node* right;
        node():val(0),left(NULL),right(NULL){}
    };
    
    node* createTree()
    {
        node* head = new node[14];
        for(int i = 0;i<10;i++)
        {
            head[i].val = i;
            if(2*i+1 < 10)
            head[i].left = head + 2*i + 1;
            if(2*i+2 < 10)
            head[i].right = head + 2*i + 2;
        }
        return head;
    }
    
    void searchfirst(node* head) ///先序遍历,其实和中序差不多,还好些
    {
        stack<node*> s;
        node* r = head;
        s.push(r);
        while(!s.empty())
        {
         while(NULL != r)
         {
             cout<<r->val<<" ";
             r = r->left;
             if(NULL != r) s.push(r);
         }
    
         r = s.top();
         s.pop();
         r = r->right;
         if(NULL != r) s.push(r);
        
        }
    }
    
    void searchmiddle(node* head)///先序遍历,其实和先序差不多,还好些
    {
        stack<node*> s;
        node* r = head;
        s.push(r);
        while(!s.empty())
        {
         while(NULL != r)
         {
             r = r->left;
             if(NULL != r) s.push(r);
         }
    
         r = s.top();
         cout<<r->val<<" ";
         s.pop();
         r = r->right;
         if(NULL != r) s.push(r);
        
        }
    }
    
    void searchlast(node* head)
    {
        stack<node* > s;
        stack<int> flags;
        int flag;
        node* p = head;
        s.push(p);
        flags.push(1);
        while(!s.empty())
        {
            while(NULL != p && NULL != p->left)///先比与前者,这个到最第的做节点就不再push了
            {
                p = p->left;
                s.push(p);
                flags.push(1);
            }
    
            flag = flags.top();
            flags.pop();
            p = s.top();
    
            if((NULL != p->right) && flag == 1)
            {
                flags.push(2);
                p = p->right;
                s.push(p);
                flags.push(1);
            }else{
                s.pop();
                cout<<p->val<<" ";
                p = NULL;
            }
        }
    }
    
    int main()
    {
     node* t = createTree();
     searchfirst(t); cout<<endl;
     searchmiddle(t); cout<<endl;
     searchlast(t); cout<<endl;
    }
    berkeleysong
  • 相关阅读:
    bzoj 2120 数颜色 带修改莫队
    luogu 2709 小B的询问 莫队
    bzoj 2002 [Hnoi2010]Bounce 弹飞绵羊 分块
    bzoj 4765 普通计算姬 dfs序 + 分块
    loj 数列分块入门 6 9(区间众数)
    loj 数列分块入门 5 7 8
    AtCoder Grand Contest 021 D
    Codeforces Round #466
    office 威胁检测
    修改macos的启动LOGO
  • 原文地址:https://www.cnblogs.com/berkeleysong/p/3746242.html
Copyright © 2011-2022 走看看