PAT练习题 P1020 Tree Traversals (25分)【树的遍历】


传送门:P1020


P1020 Tree Traversals (25分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2



题目大意:
英语太菜了,看半天没看出来是给你二叉树的后序遍历和中序遍历,让你求层序遍历(一开始还以为是求前序) =_=。


解题思路:
看懂题目后这题就不难了,只要把树建出来就行了。
我们可以利用后序遍历和中序遍历的特点(后序最后一个一定是根节点,由这个根节点可以在中序得到左子树的节点数目)递归建树。
建完树用 BFS 广搜层序即可。



AC代码:

//输入后序和中序得层序
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e3+10;
int n;
int postorder[N],inorder[N];//后序和中序
vector<int> v;
struct tree
{
  int left,right;
}tire[N];
int build(int l1,int r1,int l2,int r2)//后序-中序
{
  if(l2>r2)
    return 0;
  int root=postorder[r1];//由后序得到根节点
  int p=l2;
  while(inorder[p]!=root)//在中序中得到左子树的数目
  {
    p++;
  }
  int ans=p-l2-1;
  tire[root].left=build(l1,l1+ans,l2,p-1);//左子树递归找左子树根节点
  tire[root].right=build(l1+ans+1,r1-1,p+1,r2);//右子树递归
  return root;
}
void bfs(int x)//层序广搜
{
  queue<int> q;
  q.push(x);
  while(!q.empty())
  {
    int tmp=q.front();
    q.pop();
    v.push_back(tmp);
    if(tire[tmp].left!=0)
      q.push(tire[tmp].left);
    if(tire[tmp].right!=0)
      q.push(tire[tmp].right);
  }
}

int main()
{
  v.clear();
  scanf("%d",&n);
  for(int i=0;i<n;i++)
  {
    scanf("%d",&postorder[i]);
  }
  for(int i=0;i<n;i++)
  {
    scanf("%d",&inorder[i]);
  }
  int root=postorder[n-1];
  build(0,n-1,0,n-1);
  bfs(root);
  int len=v.size();
  for(int i=0;i<len;i++)
  {
    printf("%d%c",v[i],i==len-1?'\n':' ');
  }
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值