题目描述:
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.
输入格式:
Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.
输出格式:
For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the BST, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found…
输入样例:
6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
输出样例:
LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
题意:
给出N个结点的二叉搜索树的先序序列,给定M个测试结点对,测试每两个结点是否在二叉搜索树内,如果不在,输出没有找到,如果存在,判断它们的公共最近祖先。
思路:
由于二叉搜索树的特性:左子树的值小于根结点,右子树的值大于等于根结点,每个子树都是二叉搜索树,所以只要一个结点大于某结点A,另一个结点小于A,这两个结点的根结点就是A啦,A由先序序列遍历得到(因为先序序列是根左右嘛,首先找到的就是一个根!)。
PS:做完这道题可以顺便做下1151 LCA in a Binary Tree (30分),差不多的类型~
参考代码:
#include <stdio.h>
#include <map>
using namespace std;
const int maxn = 10010;
int m, n; //测试数,结点数
int preSeq[maxn];
map<int, int> preID;
void checkLCA(int u, int v, int preL){
int root = preSeq[preL];
if((u < root && v > root) || (u > root && v < root)){
printf("LCA of %d and %d is %d.\n", u, v, root);
}else if(u == root){
printf("%d is an ancestor of %d.\n", u, v);
}else if(v == root){
printf("%d is an ancestor of %d.\n", v, u);
}else if((u < root && v < root) || (u > root && v > root)){ //左右子树
checkLCA(u, v, preL+1);
}
}
int main(){
scanf("%d%d", &m, &n);
for(int i = 1; i <= n; i++){
scanf("%d", &preSeq[i]);
preID[preSeq[i]] = i;
}
for(int i = 0; i < m; i++){
int u, v;
scanf("%d%d", &u, &v);
if(preID[u] != 0 && preID[v] != 0){
checkLCA(u, v, 1);
}else if(preID[u] == 0 && preID[v] == 0){
printf("ERROR: %d and %d are not found.\n", u, v);
}else{
printf("ERROR: %d is not found.\n", preID[u] == 0 ? u : v);
}
}
return 0;
}