1174 Left-View of Binary Tree

The left-view of a binary tree is a list of nodes obtained by looking at the tree from left hand side and from top down. For example, given a tree shown by the figure, its left-view is { 1, 2, 3, 4, 5 }
在这里插入图片描述
Given the inorder and preorder traversal sequences of a binary tree, you are supposed to output its left-view.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N ( ≤ 20 \leq20 20), which is the total number of nodes in the tree. Then given in the following 2 lines are the inorder and preorder traversal sequences of the tree, respectively. All the keys in the tree are distinct positive integers in the range of int.

Output Specification:

For each case, print in a line the left-view of the tree. All the numbers in a line are separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.

Sample Input:

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

Sample Output:

1 2 3 4 5

思路

根据先序遍历和中序遍历建树,然后层序遍历,每层的第一个节点存下来,最后输出就是答案

cpp代码

#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
unordered_map<int,int> pos,l,r;
const int N=30;
int in[N],pre[N];
int n;
int build(int inl,int inr,int prel,int prer){
	int root=pre[prel];
	int k=pos[root];
	if(k>inl)l[root]=build(inl,k-1,prel+1,k-1-inl+prel+1);
	if(k<inr)r[root]=build(k+1,inr,k-1-inl+prel+1+1,prer); 
	return root;
}
void bfs(int root){
	queue<int> q;
	q.push(root);
	vector<int> vec;
	while(q.size()){
		int len=q.size();
		vec.push_back(q.front());
		for(int i=0;i<len;i++){
			auto t=q.front();
			q.pop();
			if(l.count(t))q.push(l[t]);
			if(r.count(t))q.push(r[t]);
		}
	}
	cout<<vec[0];
	for(int i=1;i<vec.size();i++){
		cout<<" "<<vec[i];
	}
	puts("");
	
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>in[i];
		pos[in[i]]=i;
	}
	for(int i=0;i<n;i++)cin>>pre[i];
	
	int root=build(0,n-1,0,n-1);
	
	bfs(root);
	
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值