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

#include
#include
#include
#include
#include
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;
    stacks;

    while(p||!s.empty())
    {
        while(p)
        {
            s.push(p);
            p=p->left;
        }
        if(!s.empty())
        {
            p=s.top();
            s.pop();
            cout<data<<" ";
            p=p->right;
        }
    }
}
void qianxu(Node *root)
{
    if(root==NULL)
        return ;
    Node *p=root;
    stacks;

    while(p||!s.empty())
    {
        while(p)
        {
            cout<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;
    stacks;
    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<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<

你可能感兴趣的:(二叉树非递归遍历 (前,中,后) c)