二叉树的四种遍历

二叉树的遍历:前序遍历,中序遍历,后序遍历,层次遍历。不同的遍历方式有时是解决某些问题的有效工具,比如一个计算表达式以中序存储在二叉树中,用前序遍历可以得到前缀表达式(波兰表达式),后序遍历可以得到后缀表达式(逆波兰表达式)。而最能直观展现树的二维图形的遍历则是层次遍历。下面是自己的实现代码:

<pre name="code" class="cpp">
//存储的二叉树:
 /*        1
       2       3
    4    5    6   7
   8 9 10 11            */
<pre name="code" class="cpp">
#include <iostream>
#include<cstdio>
using namespace std;
typedef struct btnode{
    struct btnode *lch,*rch;
    int date;
}bttree;
int len;
bttree *bottom=new bttree();
bttree* create(int A[],int i){
        if(i>=len)return 0;
        bttree *q=new bttree();
        q->date=A[i];
        q->lch=create(A,2*i+1);
        q->rch=create(A,2*i+2);
        return q;
}
void preorder(bttree *q){  //前序遍历
    if(q){
        cout<<q->date<<" ";
        if(q->lch)preorder(q->lch);
        if(q->rch)preorder(q->rch);    
    }
}
void inorder(bttree *q){  //中序遍历
    if(q){
        if(q->lch)inorder(q->lch);
        cout<<q->date<<" ";
        if(q->rch)inorder(q->rch);
    }
}
void postorder(bttree *q){   //后序遍历
    if(q){
        if(q->lch)postorder(q->lch);
        if(q->rch)postorder(q->rch);
        cout<<q->date<<" ";
    }
}
bttree *nq=new bttree(),queue[100];
int top=0,bn=0;  // top point and bottom point
void levelorder(bttree &q){ //层次遍历
    *nq=q;
    queue[++top]=*nq;
    while(top>bn){  // is not empty
        *nq=queue[++bn];
        cout<<nq->date<<" ";
        if(nq->lch)queue[++top]=*(nq->lch);
        if(nq->rch)queue[++top]=*(nq->rch);
    }
}
int main(int argc, char *argv[]) {
    freopen("cout.txt","w",stdout);
    int A[]={1,2,3,4,5,6,7,8,9,10,11},i=0;
    len=11;
    bottom=create(A,i);
    cout<<"there are 4 orders: "<<endl;
    cout<<"前序:"; preorder(bottom);  cout<<endl;
    cout<<"中序:"; inorder(bottom);  cout<<endl;
    cout<<"后序:"; postorder(bottom);  cout<<endl;
    cout<<"层次:"; levelorder(*bottom); cout<<endl;
    return 0;
}

 

 

输出:

there are 4 orders:
前序:1 2 4 8 9 5 10 11 3 6 7
中序:8 4 9 2 10 5 11 1 6 3 7
后序:8 9 4 10 11 5 2 6 7 3 1
层次:1 2 3 4 5 6 7 8 9 10 11


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值