[C++] PAT 1151 LCA in a Binary Tree (30分)

在这里插入图片描述

Sample Input:

6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

题解:

根据先序遍历,根左右;
以及中序遍历,左根右,
对于给定的u,v,只要确定u,v都在中序遍历中(包括u,v两个端点),那么他们的根一定是在中序遍历[u,v]中,假设i是[u,v]中的点,只要找到在先序遍历中下标最小的i,就可以确定他们的公共根

#include <iostream>
#include <map>
#include <vector>
#include <unordered_map>

using namespace std;

int n,m;
vector<int> in,pre;
map<int,int> pre_index_in;

int main(){
	cin >> n >> m;

	int temp;

	in.resize(m);
	pre.resize(m);

	for(int i=0;i<m;i++){
		scanf_s("%d",&in[i]);
		pre_index_in[in[i]] = i;
	}

	for(int i=0;i<m;i++){
		scanf_s("%d",&pre[i]);
	}

	
	for(int i=0;i<n;i++){
		int a,b;
	
		cin >> a >> b;

		int j,k;
		
		for(j=0;j<m;j++){
			if(in[j] == a) break;;
		}

		for(k=0;k<m;k++){
			if(in[k] == b) break;;
		}

		if(j >= m && k >= m ){
			printf("ERROR: %d and %d are not found.\n",a,b);
		}
		else if(j>=m){
			printf("ERROR: %d is not found.\n",a);
		}
		else if( k>=m ){
			printf("ERROR: %d is not found.\n",b);
		}

		else{
			int min_index;
			int post_i;
			for(min_index=0;min_index<m;min_index++){
				post_i = pre_index_in[pre[min_index]];
				if(post_i >= min(j,k) && post_i <= max(j,k)){
					break;
				}
			}
			
			if(post_i == j){
				printf("%d is an ancestor of %d.\n",a,b);
				
			}

			else if(post_i == k ){
				printf("%d is an ancestor of %d.\n",b,a);
				
			}

			else{
				printf("LCA of %d and %d is %d.\n",a,b,pre[min_index]);
			}

		}
	}

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值