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. Java - BlockingQueue

    https://juejin.im/post/5aeebd02518825672f19c546 https://www.infoq.cn/article/java-blocking-queue blo ...

  2. 重定向,/dev/null, 1>, 2>什么意思?

    文件描述符我们常见的就是系统预留的0,1和2这三个,他们的意义分别有如下对应关系: 0 —— stdin(标准输入) 1 —— stdout (标准输出) 2 —— stderr (标准错误) 其中, ...

  3. mac 上运行httpserver的问题

    如果你的系统是window 我建议你安装http-server 非常好用, 如果是mac,系统自带的就有httpserver 服务,没有必要在安装 按照我说的来操作 首先 sudo apachectl ...

  4. 【c++】计算句子中单词的平均长度

    Description 编程输入一行文本,计算这行文本的单词平均长度.假设每个单词用至少一个空格或者标点(英文逗号.句号)隔开.使用C++ string类型. Input 输入一行文本,不包含数字 O ...

  5. CSS中你知道的display的值有多少?用了多少?

    它的语法如下: display:none | inline | block | list-item | inline-block | table | inline-table | table-capt ...

  6. JavaSE——UDP协议网络编程(二)

    在 UDP 网络编程中,发送方与接收方没有建立联系,没有明显的服务器端和客户端的区别. 类 DatagramSocket: 此类表示用来发送和接收数据报包的套接字. 主要的构造方法: Datagram ...

  7. SG Input 软件安全分析之fuzz

    前言 前面介绍了通过静态读代码的方式去发现问题,这里介绍两种 fuzz 目标软件的方式. 相关文件 链接:https://pan.baidu.com/s/1l6BuuL-HPFdkFsVNOLpjUQ ...

  8. Android 系统工具类

    系统工具类 public class systemUtil { //隐藏ipad底部虚拟按键栏 @RequiresApi(api = Build.VERSION_CODES.KITKAT) publi ...

  9. [Linux.NET]在CentOS 7.x中编译方式安装Nginx

    Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行.由俄罗斯的程序设计师Igor Sysoev所开发,供俄罗斯大型的 ...

  10. tcpcopy用法

    目标: 将线上服务lighttpd(8000端口)的流量引流到线下测试机 一.测试机: tcpcopy-server,接收流量 modprobe ip_queue iptables -L iptabl ...