码迷,mamicode.com
首页 > 其他好文 > 详细

GPTL—练习集—006树的遍历

时间:2017-03-27 21:32:00      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:str   while   c++   evel   type   cout   its   oid   eve   

#include<bits/stdc++.h>
using namespace std;

typedef int daTp;//datatype
typedef struct BTNode *position;
typedef position BTree;
const int MAXN=30;
struct BTNode
{
    daTp data;
    position lChild,rChild;
};
BTree build(daTp in[],daTp post[],int n)//利用中序和后序遍历生成二叉树
{
    BTree T=NULL;
    if(n)
    {
        T=new BTNode;
        T->data=post[n-1];
        int ln=0,rn=0;
        bool flag=true;
        daTp lin[MAXN],lpost[MAXN],rin[MAXN],rpost[MAXN];
        for(int i=0;i<n;i++)
        {
            if(in[i]==T->data)
            {
                flag=false;
                continue;
            }
            if(flag) lin[ln++]=in[i];
            else rin[rn++]=in[i];
        }
        for(int i=0,k=0;i<n;i++)
        {
            if(i<ln) lpost[i]=post[i];
            else rpost[k++]=post[i];
        }
        T->lChild=build(lin,lpost,ln);
        T->rChild=build(rin,rpost,rn);
    }
    return T;
}
void levelOrder(BTree T)//层序遍历
{
    if(!T) return;
    queue<BTree>qu;
    qu.push(T);
    BTree tr=T;
    while(!qu.empty())
    {
        tr=qu.front();
        qu.pop();
        cout<<(tr==T?"":" ")<<tr->data;
        if(tr->lChild) qu.push(tr->lChild);
        if(tr->rChild) qu.push(tr->rChild);
    }
}
int main()
{
    int n;
    daTp inOd[MAXN],postOd[MAXN];
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
            cin>>postOd[i];
        for(int i=0;i<n;i++)
            cin>>inOd[i];
        BTree T=build(inOd,postOd,n);
        levelOrder(T);
        cout<<endl;
    }
    return 0;
}

 

GPTL—练习集—006树的遍历

标签:str   while   c++   evel   type   cout   its   oid   eve   

原文地址:http://www.cnblogs.com/Fresh--air/p/6628630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!