码迷,mamicode.com
首页 > 其他好文 > 详细

前序中序后序遍历非递归实现

时间:2014-05-26 16:14:18      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

bubuko.com,布布扣
#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;
}
bubuko.com,布布扣

 

前序中序后序遍历非递归实现,布布扣,bubuko.com

前序中序后序遍历非递归实现

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/berkeleysong/p/3746242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!