二叉树非递归遍历 (前,中,后) c

来源:互联网 发布:与美食有关的句子 知乎 编辑:程序博客网 时间:2024/06/05 02:40
#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>#include<stack>using namespace std;struct Node{    int data;    struct Node *left;    struct Node *right;    Node(int data)    {        this->data=data;        this->left=NULL;        this->right=NULL;    }};void zhongxu(Node *root){    if(root==NULL)        return ;    Node *p=root;    stack<Node *>s;    while(p||!s.empty())    {        while(p)        {            s.push(p);            p=p->left;        }        if(!s.empty())        {            p=s.top();            s.pop();            cout<<p->data<<" ";            p=p->right;        }    }}void qianxu(Node *root){    if(root==NULL)        return ;    Node *p=root;    stack<Node *>s;    while(p||!s.empty())    {        while(p)        {            cout<<p->data<<" ";            s.push(p);            p=p->left;        }        if(!s.empty())        {            p=s.top();            s.pop();            p=p->right;        }    }}void houxu(Node *root){    if(root==NULL)        return ;    Node *p=root;    stack<Node *>s;    s.push(p);    s.push(p);    while(!s.empty())    {        p=s.top();        s.pop();        if(!s.empty()&&p==s.top())        {             if(p->right) s.push(p->right), s.push(p->right);            if(p->left) s.push(p->left), s.push(p->left);        }        else            cout<<p->data<<" ";    }}int main(){    Node *p1=new Node(4);    Node *p2=new Node(7);    Node *p3=new Node(6);    Node *p4=new Node(3);    Node *p5=new Node(2);    Node *p6=new Node(5);    Node *p7=new Node(8);    Node *p8=new Node(1);    p1->left=p2;    p1->right=p3;    p2->left=p4;    p2->right=p5;    p3->left=p6;    p3->right=p7;    p7->right=p8;    zhongxu(p1);    cout<<endl;    qianxu(p1);    cout<<endl;    houxu(p1);    cout<<endl;}

阅读全文
0 0