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

posted @ 2018-12-07 09:19  xzhws  阅读(26)  评论(0编辑  收藏  举报