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. python字典按照value进行排序

    先说几个解决的方法,具体的有时间再细说 d = {'a':1,'b':4,'c':2} 字典是这个,然后要对字典按照value进行排序 方法一: sorted(d.items(),key = lamb ...

  2. Python 简单的远程执行命令

    client端执行命令,server端返回命令结果 # server 端 import socket, subprocess sk = socket.socket() address=('127.0. ...

  3. 【代码笔记】Web-HTML-框架

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  4. python第十六天,昨天来晚了,作业终于完成了

    作业 1: 员工信息表程序,实现增删改查操作 可进行模糊查询,语法至少支持下面3种: select name,age from staff_table where age > 22 select ...

  5. 【HANA系列】SAP HANA XS使用服务器JavaScript Libraries详解

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[HANA系列]SAP HANA XS使用服务器 ...

  6. CSS| 學習心得

    resize :both , 只有overflow設置為auto時, 才能起作用???

  7. MySQL5.7中的sql_mode默认值

    简介 在正常项目开发过程中,如果MySQL版本从5.6升级到5.7版本.作为DBA在考虑数据库版本升级带来的影响时,一般会有几个注意点: sql_mode 默认值的改变 optimizer_switc ...

  8. VS 2015连接SQL server数据库方法

    vs新建一个Windows窗口应用程序,界面布局如下: Form1.cs中代码如下: using System; using System.Collections.Generic; using Sys ...

  9. chrony时间服务器

    chrony有着比ntp服务器更好的优势来同步服务,在集群架构中,采用此种服务来同步时间也是最好的方式. 在集群环境中,一般都是一个服务器,然后上百个客户端来同步服务端的时间,接下来我们看看如何配置. ...

  10. Linux远程访问及控制(SSH)

    1.ssh协议:用于远程登录,端口号:22/tcp 配置文件: 1)服务器端口:/etc/ssh/sshd_config 2)客户端 :/etc/ssh/ssh_config 2.服务器监听选项: U ...