思路:
递归,给定一棵树,确认根节点是否u和v的最低公共祖先,如果不是,那么对左子树或者右子树查找。
如果u和v都存在树中,那么查找LCA,如果不是,打印对应错误信息。
先序遍历,如果当前树的根节点是u或者v,或者中序遍历序列中,根节点的位置在u和v之间,那么LCA就是根节点;
如果不是,那么中序遍历序列中,根节点的位置大于u和v,那么在左子树查找u和v的LCA,否则在右子树查找。
1151 LCA in a Binary Tree (30 point(s))
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.
Given any two nodes in a binary tree, you are supposed to find their LCA.
Example:
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
vector<int> inorder, preorder;
unordered_map<int, int> order;
int _LCA(int ib, int ie, int pb, int pe, int uin, int vin)
{
int root = order[preorder[pb]];
if(uin == root || vin == root) return inorder[root];
else if(uin > vin) {
if(vin < root && root < uin) return inorder[root];
else if(uin < root) return _LCA(ib, root, pb+1, pb+1+root-ib, uin, vin);
else return _LCA(root, ie, pb+1+root-ib, pe, uin, vin);
} else {
if(uin < root && root < vin) return inorder[root];
else if(vin < root) return _LCA(ib, root, pb+1, pb+1+root-ib, uin, vin);
else return _LCA(root, ie, pb+1+root-ib, pe, uin, vin);
}
}
int LCA(int u, int v)
{
return _LCA(0, inorder.size(), 0, preorder.size(), order[u], order[v]);
}
int main()
{
int M, N;
cin >> M >> N;
inorder.resize(N+1), preorder.resize(N+1);
for(int i = 0; i < N; i++) cin >> inorder[i], order[inorder[i]]=i;
for(int i = 0; i < N; i++) cin >> preorder[i];
for(int i = 0; i < M; i++) {
int u, v;
cin >> u >> v;
if(order.count(u) == 0 && order.count(v) == 0)
printf("ERROR: %d and %d are not found.\n", u, v);
else if(order.count(u) == 0 || order.count(v) == 0)
printf("ERROR: %d is not found.\n", order.count(u) == 0 ? u : v);
else {
int lca = LCA(u, v);
if(lca == u || lca == v) printf("%d is an ancestor of %d.\n", lca, lca == u ? v : u);
else printf("LCA of %d and %d is %d.\n", u, v, lca);
}
}
}