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

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值