题干
C++实现
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode
{
int num;
TreeNode* left;
TreeNode* right;
TreeNode* parent;
};
void createTree(vector<TreeNode*>& nodeArr, int n) {
for (int j = 1; j <= n; j++)
{
nodeArr[j] = new TreeNode;
nodeArr[j]->num = j;
}
nodeArr[1]->parent = NULL;
for (int j = 1; j <= n; j++)
{
int left, right;
cin >> left >> right;
if (left != -1) {
nodeArr[j]->left = nodeArr[left];
nodeArr[left]->parent = nodeArr[j];
}
else {
nodeArr[j]->left = NULL;
}
if (right != -1) {
nodeArr[j]->right = nodeArr[right];
nodeArr[right]->parent = nodeArr[j];
}
else {
nodeArr[j]->right = NULL;
}
}
}
int main() {
int t;//t组测试数据
cin >> t;
for (int i = 0; i < t; i++)
{
int n, m;//n是用来建树,m是用来找最短路径
cin >> n >> m;
vector<TreeNode*> nodeArr(n + 1);
createTree(nodeArr, n);
int lhs, rhs;
for (int j = 0; j < m; j++)
{
cin >> lhs >> rhs;
vector<int> lvec;
TreeNode* p = nodeArr[lhs];
while (p != NULL) {
lvec.push_back(p->num);
p = p->parent;
}
vector<int> rvec;
p = nodeArr[rhs];
while (p != NULL) {
rvec.push_back(p->num);
p = p->parent;
}
int l = lvec.size() - 1;
int r = rvec.size() - 1;
while (1) {
if (l < 0 || r < 0 || lvec[l] != rvec[r]) {
break;
}
--l;
--r;
}
cout << l + r + 2;
}
}
return 0;
}