题目链接:
https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
题目:
1020 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
解题思路:
1、给一个二叉树的中序遍历和后序遍历,输出层次遍历。
算法思想:后续遍历的最后一个节点确定根节点(从后往前遍历),在中序遍历中找到该树的下标index,将树分为左子树 [l,index-1]和右子树进行递归建树,当l>r时退出即可。
层次遍历:采用队列的方式进行遍历。
解题代码:
#include <iostream>
#include<bits/stdc++.h>
//路径:https://pintia.cn/problem-sets/994805342720868352/problems/994805489282433024
#define rep(i,s,e) for(int i = s;i<e;i++)
using namespace std;
const int MAXSIZE = 502;
int n;//子树数量
int postorder[MAXSIZE];
int inorder[MAXSIZE];
struct node{
int num;
node *left;
node *right;
};
node *dfs(int l,int r){
if(l>r) return NULL;
bool judge = true ;
int root ;
for(int i = n-1;i>=0&&judge;i--){
for(int j = l;j<=r;j++){
if(postorder[i]==inorder[j]){
root = j;
judge = false;
break;
}
}
}
node *no = new node;
no->num = inorder[root];
no->left = NULL;
no->right = NULL;
no->left = dfs(l,root-1);
no->right = dfs(root+1,r);
return no;
}
void init(){
cin>>n;
rep(i,0,n){
cin>>postorder[i];
}
rep(i,0,n){
cin>>inorder[i];
}
return ;
}
void print(node *r){
if(r==NULL) return ;
cout<<r->num<<" ";
print(r->left);
print(r->right);
}
int main( )
{
init();
node *root = new node;
root->left = dfs(0,n-1);
queue<node*> q;
q.push(root->left);
while(!q.empty()){
node *r = q.front();
q.pop();
cout<<r->num;
if(r->left!=NULL) q.push(r->left);
if(r->right!=NULL) q.push(r->right);
if(!q.empty()){
cout<<" ";
}
}
}