“侧影”就是从左侧或者右侧去观察物体所看到的内容。例如上图中男生的侧影是从他右侧看过去的样子,叫“右视图”;女生的侧影是从她左侧看过去的样子,叫“左视图”。
520 这个日子还在打比赛的你,也就抱着一棵二叉树左看看右看看了……
我们将二叉树的“侧影”定义为从一侧能看到的所有结点从上到下形成的序列。例如下图这棵二叉树,其右视图就是 { 1, 2, 3, 4, 5 },左视图就是 { 1, 6, 7, 8, 5 }。
于是让我们首先通过一棵二叉树的中序遍历序列和后序遍历序列构建出一棵树,然后你要输出这棵树的左视图和右视图。
输入格式:
输入第一行给出一个正整数 N (≤20),为树中的结点个数。随后在两行中先后给出树的中序遍历和后序遍历序列。树中所有键值都不相同,其数值大小无关紧要,都不超过 int 的范围。
输出格式:
第一行输出右视图,第二行输出左视图,格式如样例所示。
输入样例:
8
6 8 7 4 5 1 3 2
8 5 4 7 6 3 2 1
输出样例:
R: 1 2 3 4 5
L: 1 6 7 8 5
思路分析:
首先分享一下建树的知识点
这道题其实就是用中序和后续遍历建树之后,树的每一层的第一个节点就是左视图,树的每一层的最后一个节点就是右视图,因为要输出头和尾,并且每层的个数未知,所以推荐使用vector去存储。
附上代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<deque>
#include<map>
#include<set>
#define int long long
#define endl "\n"
using namespace std;
typedef pair<int,int> PII;
struct node
{
int data,left,right;
};
vector<int> in,post;
vector<int> T[100];
map<int,int> mp;
int maxl=0;
void build(int inL,int inR,int postL,int postR,int level)
{
if(inL>inR || postL>postR) return ;
int data=post[postR];
int idx=mp[data];
int l=idx-inL;
maxl=max(maxl,level);
T[level].push_back(data);
build(inL,idx-1,postL,postL+l-1,level+1);
build(idx+1,inR,postL+l,postR-1,level+1);
}
void solve()
{
int N;cin>>N;
for(int i=0;i<N;i++)
{
int x;cin>>x;
mp[x]=i;
in.push_back(x);
}
for(int i=0;i<N;i++)
{
int x;cin>>x;
post.push_back(x);
}
build(0,N-1,0,N-1,0);
cout<<"R:";
for(int i=0;i<=maxl;i++) cout<<" "<<T[i].back();
cout<<endl;
cout<<"L:";
for(int i=0;i<=maxl;i++) cout<<" "<<T[i][0];
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T=1;//cin>>T;
while(T--) solve();
}