国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

樹的遍歷 有后序遍歷和中序遍歷建立二叉樹,并輸出層次遍歷

2019-11-08 02:19:17
字體:
來源:轉載
供稿:網友
樹的遍歷   (25分)

給定一棵二叉樹的后序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這里假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數NN(/le 30≤30),是二叉樹中結點的個數。第二行給出其后序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多余空格。

輸入樣例:

72 3 1 5 7 6 41 2 3 4 5 6 7

輸出樣例:

4 1 6 3 5 7 2

#include <iostream>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <map>#include <algorithm>#include <vector>#include <string>#include <cstring>#include <sstream>using namespace std;int n;int hou[50];int zhong[50];struct Btree{    int data;    Btree* left;    Btree* right;};typedef struct Btree Btree;int findindex(int *zhong,int x,int len){    for(int i=0;i<len;i++)    {        if(zhong[i]==x)        {            return i;        }    }}Btree* build(int *hou,int *zhong,int len){    if(len<=0) return NULL;    Btree* tmp=new Btree;    tmp->data=hou[len-1];    int index=findindex(zhong,hou[len-1],len);    tmp->left=build(hou,zhong,index);    tmp->right=build(hou+index,zhong+index+1,len-index-1);    return tmp;}int ans[500];int cur;void cenorder(Btree *root){    queue<Btree*> Q;    Q.push(root);    while(!Q.empty())    {        Btree *tmp=Q.front();        ans[cur++]=tmp->data;        if(tmp->left!=NULL)        {            Q.push(tmp->left);        }        if(tmp->right!=NULL)        {            Q.push(tmp->right);        }        Q.pop();    }}int main(){    scanf("%d",&n);    for(int i=0;i<n;i++)    {        scanf("%d",&hou[i]);    }    for(int i=0;i<n;i++)    {        scanf("%d",&zhong[i]);    }    Btree *root=build(hou,zhong,n);    cenorder(root);    for(int i=0;i<n;i++)    {        if(i==0) PRintf("%d",ans[i]);        else printf(" %d",ans[i]);    }    printf("/n");    return 0;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 特克斯县| 比如县| 府谷县| 西峡县| 卓尼县| 敦化市| 林西县| 永平县| 通道| 奉节县| 蕉岭县| 吴堡县| 新乡县| 盱眙县| 南郑县| 安仁县| 正安县| 科技| 新巴尔虎左旗| 津市市| 莲花县| 南溪县| 蒲江县| 大埔县| 碌曲县| 游戏| 云和县| 济南市| 仁怀市| 滦南县| 寻甸| 敦化市| 日喀则市| 海盐县| 体育| 靖西县| 平罗县| 韩城市| 乐至县| 邯郸县| 彭山县|