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.

Input Specification:

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 binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:

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 Xis A and Y is the other node. If U or V is not found in the binary tree, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

Sample Input:

6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

 #include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int maxn=;
int n,m,k;
int inorder[maxn],preorder[maxn];
struct node{
int data;
node* left;
node* right;
};
node* create(int prel,int prer,int inl,int inr){
if(prel>prer){
return NULL;
}
node* root=new node;
root->data=preorder[prel];
int k;
for(k=inl;k<=inr;k++){
if(inorder[k]==preorder[prel]){
break;
}
}
int numleft=k-inl;
root->left = create(prel+,prel+numleft,inl,k-);
root->right = create(prel+numleft+,prer,k+,inr);
return root;
}
bool findnode(int x){
for(int i=;i<m;i++){
if(preorder[i]==x) return true;
}
return false;
}
node* lca(node* root,int x1,int x2){
if(root==NULL)return NULL;
if(root->data==x1 || root->data==x2) return root;
node* left = lca(root->left,x1,x2);
node* right = lca(root->right,x1,x2);
if(left && right) return root;
else if(left==NULL) return right;
else return left;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=;i<m;i++){
int c1;
scanf("%d",&c1);
inorder[i]=c1;
}
for(int i=;i<m;i++){
int c1;
scanf("%d",&c1);
preorder[i]=c1;
}
node *root=create(,m-,,m-);
for(int i=;i<n;i++){
int x1,x2;
scanf("%d %d",&x1,&x2);
if(!findnode(x1) && !findnode(x2)){
printf("ERROR: %d and %d are not found.\n",x1,x2);
}
else if(!findnode(x1)) printf("ERROR: %d is not found.\n",x1);
else if(!findnode(x2)) printf("ERROR: %d is not found.\n",x2);
else{
node* res = lca(root,x1,x2);
if(res->data == x1) printf("%d is an ancestor of %d.\n",x1,x2);
else if(res->data == x2) printf("%d is an ancestor of %d.\n",x2,x1);
else printf("LCA of %d and %d is %d.\n",x1,x2,res->data);
}
}
}

注意点:lca居然可以迭代做出来,实在是厉害,看了好久终于看懂了一点吧,考前要再背一下。一开始想的是把指定点的祖先都获得存在一个vector里,然后从后往前比较两个vector,第一个相同的就是他们的lca,但调试了半天一直报错,vector的index超出范围,不知道为什么,总感觉是对的,代码贴在下面,有大佬看到还请指点一下。

第二点的话就是二叉树的建立一定要熟悉,虽然这道题可以不用建树就做出来。

 #include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int maxn = ;
int n, m, k, q = ;
int inorder[maxn], preorder[maxn];
vector<int> v, v1[];
struct node {
int data;
node* left;
node* right;
};
node* create(int prel, int prer, int inl, int inr) {
if (prel > prer) {
return NULL;
}
node* root = new node;
root->data = preorder[prel];
int k;
for (k = inl; k <= inr; k++) {
if (inorder[k] == preorder[prel]) {
break;
}
}
int numleft = k - inl;
root->left = create(prel + , prel + numleft, inl, k - );
root->right = create(prel + numleft + , prer, k + , inr);
return root;
}
void search(node* root, int x) {
if (root == NULL) return;
v.push_back(root->data);
if (root->data == x) {
for (int i = ; i < v.size(); i++) {
v1[q].push_back(v[i]);
}
v.pop_back();
return;
}
search(root->left, x);
search(root->right, x);
v.pop_back();
}
int main() {
scanf("%d %d", &n, &m);
for (int i = ; i < m; i++) {
int c1;
scanf("%d", &c1);
inorder[i] = c1;
}
for (int i = ; i < m; i++) {
int c1;
scanf("%d", &c1);
preorder[i] = c1;
}
node *root = new node;
root = create(, m - , , m - );
for (int i = ; i < n; i++) {
int x1, x2;
scanf("%d %d", &x1, &x2);
v1[].clear();
v1[].clear();
v.clear();
q = ;
search(root, x1);
q = ;
v.clear();
search(root, x2);
if (v1[].empty() && v1[].empty()) {
printf("ERROR: %d and %d are not found.\n", x1, x2);
}
else if (v1[].empty()) printf("ERROR: %d is not found.\n", x1);
else if (v1[].empty()) printf("ERROR: %d is not found.\n", x2);
else {
for (int j = v1[].size() - ; j >= ; j++) {
for (int k = v1[].size() - ; k >= ; k++) {
if (v1[][j] == v1[][k]) {
if (j == v1[].size() - ) printf("%d is an ancestor of %d.\n", x1, x2);
else if (k == v1[].size() - ) printf("%d is an ancestor of %d.\n", x2, x1);
else printf("LCA of %d and %d is %d.\n", x1, x2, v1[][j]);
}
}
}
}
}
}

PAT A1151 LCA in a Binary Tree (30 分)——二叉树,最小公共祖先(lca)的更多相关文章

  1. PAT Advanced 1151 LCA in a Binary Tree (30) [树的遍历,LCA算法]

    题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both ...

  2. PAT-2019年冬季考试-甲级 7-4 Cartesian Tree (30分)(最小堆的中序遍历求层序遍历,递归建树bfs层序)

    7-4 Cartesian Tree (30分)   A Cartesian tree is a binary tree constructed from a sequence of distinct ...

  3. PAT甲级|1151 LCA in a Binary Tree 先序中序遍历建树 lca

    给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近 ...

  4. Network-POJ3694(最小公共祖先LCA+Tarjin)

    http://poj.org/problem?id=3694 这一题  为什么要找最小祖先呢 当两个节点连到一块的时候  找最小公共节点就相当于找强连通分支 再找最小公共节点的过程中直到找到  这个过 ...

  5. 【PAT甲级】1110 Complete Binary Tree (25分)

    题意: 输入一个正整数N(<=20),代表结点个数(0~N-1),接着输入N行每行包括每个结点的左右子结点,'-'表示无该子结点,输出是否是一颗完全二叉树,是的话输出最后一个子结点否则输出根节点 ...

  6. Jamie and Tree (dfs序 + 最近公共祖先LCA)

    题面 题解 我们求它子树的权值和,一般用dfs序把树拍到线段树上做. 当它换根时,我们就直接把root赋值就行了,树的结构不去动它. 对于第二个操作,我们得到的链和根的相对位置有三种情况: 设两点为A ...

  7. PAT_A1151#LCA in a Binary Tree

    Source: PAT A1151 LCA in a Binary Tree (30 分) Description: The lowest common ancestor (LCA) of two n ...

  8. 【PAT 甲级】1151 LCA in a Binary Tree (30 分)

    题目描述 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has bo ...

  9. PAT 1151 LCA in a Binary Tree[难][二叉树]

    1151 LCA in a Binary Tree (30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is ...

随机推荐

  1. 【常用配置】Spring框架web.xml通用配置

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java. ...

  2. WCF Service 转换为Web Service 中字段属性

    1.新建WCF服务,服务中包含对象 2.部署WCF服务,并将其转换为应用程序 3.通过添加服务引用,使用WCF服务 4.调用对应的对象时需要对应的值设置为True. 参考:https://cloud. ...

  3. 实现Java Socket 客户端服务端交互实例

    SocketService.java package socket; import java.io.BufferedReader; import java.io.IOException; import ...

  4. SQL Server 基本SELECT语句

    1.SELECT 和 FROM 语句 SELECT表示执行的是查询,接着需要更知道从哪边查询数据,FROM就是限制读取的数据在哪一个表或哪几个表中,这样就构成了一个基本语句. SELECT * FRO ...

  5. canvas-arc.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. (网页)Java程序员们最常犯的10个错误(转)

    转自CSDN: 1.将数组转化为列表 将数组转化为一个列表时,程序员们经常这样做: List<String> list = Arrays.asList(arr); Arrays.asLis ...

  7. CSS3创建圆圈进度条

    最近在工作中需要做一个圆圈倒计时,刚开始的想法是做个纯数字的倒计时即可,可是需求觉得这个不太好看,想加个倒计时进度条.于是就有了接下来的分析过程... 我们知道CSS3可以很方便的画圆,圆环,然后在加 ...

  8. Azure 标准与高级托管磁盘存储的相互转换

    托管磁盘提供两种存储选项:高级(基于 SSD)和标准(基于 HDD). 它允许基于性能需求在这两个选项之间轻松切换,并保障最短停机时间. 非托管磁盘不具备此功能. 但可以轻松转换为托管磁盘,以便在这两 ...

  9. Windows:添加、删除和修改静态路由

    添加一条路由 route add 删除一条路由 route add -p #作用同上,只是这是一条永久路由,不会因为重启机器而丢失.  注意:如果有两条路由记录有着相同的“目的网络号”,则会将两条记录 ...

  10. Django 项目连接数据库Mysql要安装mysqlclient驱动出错 : Failed building wheel for mysqlclient:

    1,如果直接用 CMD命令:pip install mysqlclient ,会安装出错. 2,解决问题,参考了这个博友的帖子:https://blog.csdn.net/qq_29784441/ar ...