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;
			}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章