PTA甲级考试真题练习151——1151 LCA in a Binary Tree

题目

在这里插入图片描述

思路

和1143差不多,主要是查找函数有变化,这个是要每次将整颗树遍历一遍,而1141是遍历到结点就行了。

代码

测试点1有误,望大神解答

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool found1 = false, found2 = false;
vector<int> pre, in;
typedef struct node {
	int val;
	node* lchild, * rchild;
}*tree;
void init(tree& t, int low, int high, int cur) {
	if (low > high)
		return;
	t = new node();
	t->val = pre[cur];
	t->lchild = t->rchild = nullptr;
	int _index = low;
	while (_index <= high && in[_index] != pre[cur]) ++_index;
	int bias = _index - low;
	init(t->lchild, low, _index - 1, cur + 1);
	init(t->rchild, _index + 1, high, cur + bias + 1);
}
void find1(vector<int>& vec, tree& t, int val) {
	if (t->val == val) {
		found1 = true;
		return;
	}
	if (t->lchild != nullptr) {
		if (!found1)
			vec.emplace_back(t->lchild->val);
		find1(vec, t->lchild, val);
		if (!found1)
			vec.pop_back();
	}
	if (t->rchild != nullptr) {
		if (!found1)
			vec.emplace_back(t->rchild->val);
		find1(vec, t->rchild, val);
		if (!found1)
			vec.pop_back();
	}
}
void find2(vector<int>& vec, tree& t, int val) {
	if (t->val == val) {
		found2 = true;
		return;
	}
	if (t->lchild != nullptr) {
		if (!found2)
			vec.emplace_back(t->lchild->val);
		find2(vec, t->lchild, val);
		if (!found2)
			vec.pop_back();
	}
	if (t->rchild != nullptr) {
		if (!found2)
			vec.emplace_back(t->rchild->val);
		find2(vec, t->rchild, val);
		if (!found2)
			vec.pop_back();
	}
}
int main()
{
	int n, qn;
	cin >> qn >> n;
	pre.resize(n);
	in.resize(n);
	for (int i = 0; i < n; ++i) cin >> in[i];
	for (int i = 0; i < n; ++i) cin >> pre[i];
	tree t;
	init(t, 0, n - 1, 0);
	for (int i = 0; i < qn; ++i) {
		int u, v;
		cin >> u >> v;
		vector<int> vec1, vec2;
		find1(vec1, t, u);
		find2(vec2, t, v);
		if (!found1 && !found2) {
			cout << "ERROR: " << u << " and " << v << " are not found." << endl;
			found1 = found2 = false;
			continue;
		}
		else if (!found1 && found2) {
			cout << "ERROR: " << u << " is not found." << endl;
			found1 = found2 = false;
			continue;
		}
		else if (found1 && !found2) {
			cout << "ERROR: " << v << " is not found." << endl;
			found1 = found2 = false;
			continue;
		}
		bool flag = false;
		int tar, j;
		for (j = 0; j < vec1.size() && j < vec2.size(); ++j) {
			if (vec1[j] != vec2[j]) {
				flag = true;
				tar = vec1[j - 1];
				break;
			}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值