7-3 Left-View of Binary Tree (25 分)

7-3 Left-View of Binary Tree (25 分)

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 }

fig.JPG

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), 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
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<queue>
#include<set>
using namespace std;
const int maxn = 20;
int in[maxn],pre[maxn];
int n;
struct node{
	int data;
	node* lchild;
	node* rchild;
	int level;
};
node* createTree(int preL,int preR,int inL,int inR)
{
	if(preL>preR) return NULL;
	node* root=(node*)malloc(sizeof(struct node));
	root->data = pre[preL];
	int i;
	for(i=inL; i<=inR; i++){
		if(in[i]==pre[preL]) break;
	}
	int k=i-inL;
	root->lchild=createTree(preL+1,preL+k,inL,i-1);
	root->rchild=createTree(preL+k+1,preR,i+1,inR);
	return root;
} 
vector<int> ans;
void level(node* root)
{
	set<int> s;
	queue<node*> q;
	root->level = 1;
	q.push(root);
	node* tmp;
	while(!q.empty()){
		tmp = q.front();q.pop();
		if(s.count(tmp->level)==0){
			s.insert(tmp->level);
			ans.push_back(tmp->data);
		}
		if(tmp->lchild){
			tmp->lchild->level = tmp->level+1;
			q.push(tmp->lchild);
		}
		if(tmp->rchild){
			tmp->rchild->level = tmp->level+1;
			q.push(tmp->rchild);
		}
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=0; i<n; i++){
		scanf("%d",&in[i]);
	}
	for(int i=0; i<n; i++){
		scanf("%d",&pre[i]);
	}
	node* root = createTree(0,n-1,0,n-1);
	level(root);
	for(int i=0; i<ans.size(); i++){
		printf("%d",ans[i]);
		if(i!=ans.size()-1) printf(" ");
		else printf("\n");
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值