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…
题意:给出m对结点和二叉查找树的先序序列,求要查的两对结点的最近祖先。 思路:这是一棵二叉搜索树,参考了柳神的博客后发现好简单,只要先把这个先序序列存下来,然后在这个先序序列中找到比大于等于u,小于等于v或者大于等于v小于等于u的数,这个树就是这两个结点的最近祖先,然后只要判断一下当前遍历到的先序序列中的某一个数与u,v有没有重合或者不存在的情况就可以了
#include<iostream> #include<cstdio> #include<stack> #include<queue> #include<vector> #include<algorithm> #include<cstring> #include<string> #include<cmath> #include<set> #include<map> #include<cctype> #include<cstdlib> #include<ctime> #include<unordered_map> using namespace std; int main() { int m,n,a; scanf("%d%d",&m,&n); int pre[10010]; map<int,bool> map; for(int i = 0;i < n;i++) { scanf("%d",&pre[i]); map[pre[i]] = true; } for(int i = 0;i < m;i++) { int u,v; scanf("%d%d",&u,&v); for(int j = 0;j < n;j++) { a = pre[j]; if((pre[j] <= u && pre[j] >= v) || (pre[j] <= v && pre[j] >= u)) break; } if(map[u] == false && map[v] == false) { printf("ERROR: %d and %d are not found.\n",u,v); } else if(map[u] == false || map[v] == false) { printf("ERROR: %d is not found.\n",map[u] == false ? u : v); } else if(a == u || a == v) { printf("%d is an ancestor of %d.\n",a,a == u ? v : u); } else { printf("LCA of %d and %d is %d.\n",u,v,a); } } return 0; }