PAT 1143 Lowest Common Ancestor

题目链接:
PAT 1143 Lowest Common Ancestor

题意:
给定二叉搜索树的先序遍历,求二叉树中任意两个节点的最近父节点。

思路:
一言不合就建树,然后开始用最近父节点的方法搜索两个节点的父节点。然而后面三个点超时了…原来给了二叉搜索树的先序遍历后,直接扫一遍先序遍历的集合,满足当前节点在给定的两个节点之间即可。
code:

#include <iostream>
#include<cstdio>
#include<unordered_map>
#include<vector>
using namespace std;
unordered_map<int,int> mp;
vector<int> v;
int main(int argc, char** argv) {
	int m,n;
	scanf("%d %d",&m,&n);
	for(int i=0;i<n;i++){
		int x;
		scanf("%d",&x);
		mp[x]=1;
		v.push_back(x);
	}
	while(m--){
		int a,b;
		scanf("%d %d",&a,&b);
		if(!mp[a]&&(!mp[b]))
			printf("ERROR: %d and %d are not found.\n",a,b);
		else if(!mp[a]&&mp[b]) printf("ERROR: %d is not found.\n",a);
		else if(mp[a]&&(!mp[b])) printf("ERROR: %d is not found.\n",b);
		else{
			int ans;
			for(int i=0;i<v.size();i++){
				if((v[i]>=a&&v[i]<=b)||(v[i]>=b&&v[i]<=a)){//满足就退出
					ans=v[i];
					break;
				}
			}
			if(ans!=a&&(ans!=b)) printf("LCA of %d and %d is %d.\n",a,b,ans);
			else if(ans!=a) printf("%d is an ancestor of %d.\n",ans,a);
			else printf("%d is an ancestor of %d.\n",ans,b);
		}
	}
	return 0;
}

code 2: 建树后再搜索超时后面三个点…

#include <iostream>
#include<cstdio>
#include<unordered_map>
using namespace std;
struct node{
	int v;
	node *left,*right;
};
unordered_map<int,int> mp;
node *build(node *root,int v){
	if(root==NULL){
		root=new node();
		root->v=v;
		root->left=root->right=NULL;
		return root;
	}
	if(v>=root->v)
		root->right=build(root->right,v);
	else
		root->left=build(root->left,v);
	return root;
}
node *findancestor(node *root,int a,int b){
	if(root==NULL) return root;
	if(root->v==a) {
		return root;
	}
	if(root->v==b){
		return root;
	}
	node *left=findancestor(root->left,a,b);
	node *right=findancestor(root->right,a,b);
	
	if(left!=NULL&&(right!=NULL)) return root;
	if(left==NULL) return right;
	if(right==NULL) return left;
}
int main(int argc, char** argv) {
	int m,n;
	scanf("%d %d",&m,&n);
	node *root=NULL;
	for(int i=0;i<n;i++){
		int x;
		scanf("%d",&x);
		mp[x]=1;
		root=build(root,x);
	}
	while(m--){
		int a,b;
		scanf("%d %d",&a,&b);
		if(!mp[a]&&(!mp[b]))
			printf("ERROR: %d and %d are not found.\n",a,b);
		else if(!mp[a]&&mp[b]) printf("ERROR: %d is not found.\n",a);
		else if(mp[a]&&(!mp[b])) printf("ERROR: %d is not found.\n",b);
		else{
			node *ans=findancestor(root,a,b);
			if(ans!=NULL){
				if(ans->v!=a&&(ans->v!=b)) printf("LCA of %d and %d is %d.\n",a,b,ans->v);
				else if(ans->v==a) printf("%d is an ancestor of %d.\n",ans->v,b);
				else printf("%d is an ancestor of %d.\n",ans->v,a);
			}
		}
	}
	return 0;
}

第一部分的想法参考自:
https://www.liuchuo.net/archives/4616

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值