二叉树的先序建立与非递归遍历C++版

本文详细介绍了如何通过非递归方式实现二叉树的先序、中序和后序遍历,包括使用栈的数据结构进行操作,避免了递归带来的内存消耗,展示了算法在数据结构领域的巧妙应用。

有些知识别管它有没有用,别管它是否有利于你的就业,尤其是数学知识,用心去体会,一定有收获

 

 

 

#include<iostream>
using namespace std;
class tree
{
    public:
    char data;
    int tag;
    class tree *lchild;
    class tree *rchild;
};
tree* build()//先序建树
{
     char c;
     cin>>c;
     tree *t;
     if(c=='#')
     {
           t=NULL;
     }
     else
     {
          t=new tree;
          t->data=c;
          t->lchild = build();
          t->rchild = build();
     }
     return t;
}
class stack
{
    public:
    tree *top,*base;
};
void init (stack *s)//初始化栈
{
     s->base=new tree[100];
     s->top=s->base;
}
void push(stack *s,tree *t)//入栈
{
     *(s->top++)=*t;
}
void pop(stack *s,tree *&t)//删除栈顶元素
{
     *t=*(--(s->top));
}
void gettop(stack *s,tree *&t)//取栈顶元素
{
    *t= *(s->top-1);
}
void preorder(tree *t)//非递归先序遍历
{
    stack *s=new stack;
    tree *p;
    tree *temp=new tree;
    p=t;
    init(s);
    while(p!=NULL||s->top!=s->base)
    {
        if(p!=NULL)
        {
            cout<<p->data;
            push(s,p);
            p=p->lchild;
        }
        else
        {
            pop(s,temp);
            p=temp->rchild;
        }
    }
}
void inorder(tree *t)//非递归中序遍历
{
     stack *s=new stack;
     tree *p;
     init(s);
     p=t;
     tree *temp=new tree;
     while(p||s->top!=s->base)
     {
          if(p)
          {
               push(s,p);
               p=p->lchild;
          }
          else
          {
               pop(s,temp);
               cout<<temp->data;
               p=temp->rchild;
          }
     }
}
void postorder(tree *t)//非递归后序遍历
{
     int tag;
     stack *s=new stack;
     init(s);
     while(t!=NULL||s->top!=s->base)
     {
          while(t!=NULL)
          {
               t->tag=0;
               push(s,t);
               t=t->lchild;
          }
          t=new tree;
          while(s->top!=s->base&&(s->top-1)->tag==1)
          {
               pop(s,t);
               cout<<t->data;
          }
          if(s->top!=s->base)
          {
              (s->top-1)->tag=1;
               gettop(s,t);
               t=t->rchild;
          }
          else
              break;
    }
}
int main()
{
     tree *t;
     t = build();
     cout<<"非递归先序遍历"<<endl;
     preorder(t);
     cout<<endl;
     cout<<"非递归中序遍历"<<endl;
     inorder(t);
     cout<<endl;
     cout<<"非递归后续遍历"<<endl;
     postorder(t);
     cout<<endl;
     return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值