码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 2020年秋季 7-3 Left-View of Binary Tree (25 分)

时间:2021-03-11 18:26:16      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:front   void   struct   root   amp   bfs   beginning   lin   int   

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), 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

实现思路:

没得说,这么简单当时自己都没做全对,九月那次应该是被第一题打死了,直接就崩了,就很简单的利用层序遍历输出第一个结点就可以了。

AC代码:

#include <iostream>
#include <queue>
using namespace std;
const int N=30;
int in[N],pre[N];
struct node {
	int data,high;
	node *l,*r;
};

node* build(int preL,int preR,int inL,int inR) {
	if(preL>preR) return NULL;
	node *root=new node;
	root->data=pre[preL];
	int k;
	for(k=inL; k<=inR; k++) {
		if(root->data==in[k]) break;
	}
	int leftNodeNum=k-inL;
	root->l=build(preL+1,preL+leftNodeNum,inL,k-1);
	root->r=build(preL+leftNodeNum+1,preR,k+1,inR);
	return root;
}
int maxHigh=-1,vist[N]= {0};//maxHigh暴力树的最大高度

void bfs(node *root) {
	queue<node*> q;
	q.push(root);
	root->high=1;//设置根节点高度
	while(!q.empty()) {
		node *now=q.front();
		if(now->high>maxHigh) maxHigh=now->high;
		if(!vist[now->high]) vist[now->high]=now->data;
		q.pop();
		if(now->l) {
			now->l->high=now->high+1;
			q.push(now->l);
		}
		if(now->r) {
			now->r->high=now->high+1;
			q.push(now->r);
		}
	}
}

int main() {
	int n;
	cin>>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=build(0,n-1,0,n-1);
	bfs(root);
	for(int i=1; i<=maxHigh; i++) {
		printf("%d",vist[i]);
		if(i<maxHigh) printf(" ");
	}
	return 0;
}

PAT 2020年秋季 7-3 Left-View of Binary Tree (25 分)

标签:front   void   struct   root   amp   bfs   beginning   lin   int   

原文地址:https://www.cnblogs.com/coderJ-one/p/14514437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!