1143 Lowest Common Ancestor (30分)/先序遍历和二叉搜索树的特点

题目描述

在这里插入图片描述在这里插入图片描述

题目大意

给定二叉搜索树的先序遍历,该二叉树的key都是唯一的。给定一对key值,要求这对key值所在结点的深度最大的祖先。

分析

我的思路是通过递归,确定每个key值对应的搜索路径(如果存在该结点),通过比较两个节点的搜索路径,路径中最后一个相同的结点即为所求。
由于递归算法比较耗时,所以有两个测试点无法通过…

#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<unordered_set>
#include<unordered_map>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
vector<int> v;
vector<int> path1, path2;
bool flag;
bool search(int &key,int left,int right) {
	if (left > right) return false;
	if (!flag) path1.push_back(v[left]);
	else path2.push_back(v[left]);
	if (key == v[left]) return true;
	int k = left+1;
	while (k <= right && v[k] < v[left]) k++;
	if (key > v[left]) return search(key, k, right);
	else return search(key, left + 1, k - 1);
}
int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif
	int m, n; cin >> m >> n;
	v.resize(n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &v[i]);
	}
	while (m--) {
		int a, b;
		scanf("%d %d", &a, &b);
		path1.clear(); path2.clear();
		flag = 0; bool flag1 = search(a,0,n-1);
		flag = 1;bool flag2= search(b,0,n-1);
		if (flag1 == 0 && flag2 == 0) printf("ERROR: %d and %d are not found.\n", a, b);
		else if (flag1 == 0) printf("ERROR: %d is not found.\n", a);
		else if (flag2 == 0) printf("ERROR: %d is not found.\n", b);
		else {
			int i;
			for (i = 0; i < path1.size() && i < path2.size(); i++) {
				if (path1[i] != path2[i]) break;
			}
			if (i == path1.size()) printf("%d is an ancestor of %d.\n", a, b);
			else if (i == path2.size()) printf("%d is an ancestor of %d.\n", b, a);
			else printf("LCA of %d and %d is %d.\n", a, b, path1[i - 1]);
		}
	}
	return 0;
}

这里参考柳神的思路,真的是简单多了~
由于先序遍历是先给出根节点,所以可以通过二叉搜索树的性质,确定LCA,这个过程其实就是,找到第一个将两个key分到两个子树上的这样一个结点。

#include<iostream>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<unordered_set>
#include<unordered_map>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
vector<int> v;
unordered_map<int, bool> mapp;
int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif
	int m, n, a, b, t; cin >> m >> n;
	v.resize(n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &v[i]);
		mapp[v[i]] = 1;
	}
	while (m--) {
		scanf("%d%d", &a, &b);
		for (int i = 0; i < v.size(); i++) {
			t = v[i];
			if (t > a&&t<b || t>b&&t < a || t == a || t == b) break;
		}
		if (mapp[a] == 0 && mapp[b] == 0) printf("ERROR: %d and %d are not found.\n", a, b);
		else if (mapp[a] == 0 || mapp[b] == 0) {
			printf("ERROR: %d is not found.\n", mapp[a] == 0 ? a : b);
		}
		else if (t == a || t == b) {
			printf("%d is an ancestor of %d.\n", t, t == a ? b : a);
		}
		else printf("LCA of %d and %d is %d.\n", a, b, t);
	}
	return 0;
}
发布了103 篇原创文章 · 获赞 9 · 访问量 4703

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104408128