倍增求LCA
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define REP(i, l, r) for (int i = l; i >= r; i--)
#define MAXN 200010
#define M 20
int n, root, first[MAXN], next[MAXN], N, father[MAXN], fa[MAXN][M+3], deep[MAXN];
struct edge {int x, y;} a[2*MAXN];
bool vis[MAXN];
inline int read() {
int x = 0, f = 1; char ch = getchar();
while (ch<'0' || ch>'9') {if (ch == '-') f = -1; ch = getchar();}
while (ch>='0' && ch<='9') x = x*10 + ch - '0', ch = getchar();
return x*f;
}
inline void dfs(int x, int d) {
vis[x] = 1;
deep[x] = d;
for (int i = first[x]; ~i; i = next[i])
if (!vis[a[i].y])
dfs(a[i].y, d+1);
}
inline void init(int root) {
memset(vis, 0, sizeof(vis));
dfs(root, 1);
rep(j, 1, M) rep(i, 1, n) fa[i][j] = fa[ fa[i][j-1] ][j-1];
}
inline void add(int x, int y) {a[++N].x = x, a[N].y = y, next[N] = first[x], first[x] = N;}
inline int lca(int x, int y) {
if (deep[x] < deep[y]) swap(x, y);
int delta = deep[x] - deep[y];
rep(j, 0, M) if ((1<<j) & delta) x = fa[x][j];
if (x == y) return x;
REP(j, M, 0) if (fa[x][j] != fa[y][j]) x = fa[x][j], y = fa[y][j];
return fa[x][0];
}
int main() {
int T_T = read();
while (T_T--) {
N = -1;
memset(first, -1, sizeof(first));
memset(fa, 0, sizeof(father));
n = read();
rep(i, 1, n-1) {
int tx = read(), ty = read();
add(tx, ty), add(ty, tx);
fa[ty][0] = tx;
if (!fa[tx][0]) root = tx;
}
init(root);
int tx = read(), ty = read();
printf("%d\n", lca(tx, ty));
}
return 0;
}