1020 Tree Traversals

在这里插入图片描述

题目大意:

给你二叉树结点数和后序,中序遍历结果,要求输出层次遍历的结果。

解题思路:

二叉树板子题,根据后序中序构建二叉树,然后通过BFS遍历输出层次序列即可。
代码如下:

#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
//vector ::iterator it;
//set<int>::iterator iter;
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int n,pos[50],in[50];//后序,中序遍历序列
struct node
{
  int data;
  node* lchild;
  node* rchild;
};
node* create(int posl,int posr,int inl,int inr)//由后序,中序构建二叉树
{
  if(posl>posr)return NULL;
  node* root=new node;//申请新的node型结点
  root->data=pos[posr];
  int k;
  for(int i=inl;i<=inr;i++)//寻找根节点
  {
    if(in[i]==root->data)
    {
      k=i;
      break;
    }
  }
  int numleft=k-inl;//左子树长度
  root->lchild=create(posl,posl+numleft-1,inl,inl+numleft-1);//递归建立左子树
  root->rchild=create(posl+numleft,posr-1,k+1,inr);//递归建立右子树
  return root;
}
void bfs(node* root)//广搜输出层次遍历序序列
{
  queue<node*>q;
  q.push(root);
  int num=1;
  while(!q.empty())
  {
    node* pri=q.front();
    cout<<pri->data;
    num++;
    if(num<=n)cout<<' ';
    q.pop();
    if(pri->lchild!=NULL)q.push(pri->lchild);
    if(pri->rchild!=NULL)q.push(pri->rchild);
  }
  cout<<endl;
}
int main()
{
//  std::ios::sync_with_stdio(false);
//  cin.tie(0);
//  freopen("test.txt","r",stdin);
//  freopen("output.txt","w",stdout);
 cin>>n;
 for(int i=0;i<n;i++)cin>>pos[i];
 for(int i=0;i<n;i++)cin>>in[i];
 node* root=create(0,n-1,0,n-1);
 bfs(root);
 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值