思路:
1. 对 BST 的先序排列,进行递增排序,得到中序排列,利用先序+中序,可得整棵 BST
2. 如果在中序排列中,根结点处于X和Y之间,那么根节点就是 LCA,否则在左子树,或者右子树
1143 Lowest Common Ancestor (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.
A binary search tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
Given any two nodes in a BST, you are supposed to find their LCA.
Example:
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
int lca(vector<int> &pre, vector<int> &in,
int preBegin, int preEnd,
int inBegin, int inEnd,
int x, int y)
{
if(preBegin >= preEnd) return 0;
int root = pre[preBegin];
if((x <= root && root <= y) || (y <= root && root <= x) ) {
return root;
} else {
int len = inEnd - inBegin - 1;
for( ; len >= 0; len--) if(in[inBegin+len] == root) break;
if(x < root) {
return lca(pre, in, preBegin+1, preBegin+len+1, inBegin, inBegin+len, x, y);
} else {
return lca(pre, in, preBegin+len+1, preEnd, inBegin+len+1, inEnd, x, y);
}
}
}
int main()
{
int M, N;
cin >> M >> N;
vector<int> preorder(N);
set<int> s1;
for(int i = 0; i < N; i++) {
cin >> preorder[i];
s1.insert(preorder[i]);
}
vector<int> inorder = preorder;
sort(inorder.begin(), inorder.end());
for(int i = 0; i < M; i++) {
int X, Y;
cin >> X >> Y;
int XC = s1.count(X), YC = s1.count(Y);
if(XC > 0 && YC > 0) {
int ans = lca(preorder, inorder, 0, N, 0, N, X, Y);
if(ans == X) {
printf("%d is an ancestor of %d.\n", X, Y);
} else if(ans == Y) {
printf("%d is an ancestor of %d.\n", Y, X);
} else {
printf("LCA of %d and %d is %d.\n", X, Y, ans);
}
} else {
if(XC == 0 && YC == 0) {
printf("ERROR: %d and %d are not found.\n", X, Y);
} else if(XC == 0) {
printf("ERROR: %d is not found.\n", X);
} else {
printf("ERROR: %d is not found.\n", Y);
}
}
}
}