PAT A1151 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 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)的更多相关文章
- 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 ...
- 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 ...
- PAT甲级|1151 LCA in a Binary Tree 先序中序遍历建树 lca
给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近 ...
- Network-POJ3694(最小公共祖先LCA+Tarjin)
http://poj.org/problem?id=3694 这一题 为什么要找最小祖先呢 当两个节点连到一块的时候 找最小公共节点就相当于找强连通分支 再找最小公共节点的过程中直到找到 这个过 ...
- 【PAT甲级】1110 Complete Binary Tree (25分)
题意: 输入一个正整数N(<=20),代表结点个数(0~N-1),接着输入N行每行包括每个结点的左右子结点,'-'表示无该子结点,输出是否是一颗完全二叉树,是的话输出最后一个子结点否则输出根节点 ...
- Jamie and Tree (dfs序 + 最近公共祖先LCA)
题面 题解 我们求它子树的权值和,一般用dfs序把树拍到线段树上做. 当它换根时,我们就直接把root赋值就行了,树的结构不去动它. 对于第二个操作,我们得到的链和根的相对位置有三种情况: 设两点为A ...
- 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 ...
- 【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 ...
- 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 ...
随机推荐
- Java8的lambda表达式和Stream API
一直在用JDK8 ,却从未用过Stream,为了对数组或集合进行一些排序.过滤或数据处理,只会写for循环或者foreach,这就是我曾经的一个写照. 刚开始写写是打基础,但写的多了,各种乏味,非过来 ...
- spline和Pchips的不同(matlab)
这是一条官方的链接:http://blogs.mathworks.com/cleve/2012/07/16/splines-and-pchips/ 主要是比较在matlab中spline和Pchips ...
- python之成员(面向对象)
1. 成员 在类中你能写的所有内容都是类的成员 class Person: def __init__(self, name, gender): self.name = name # 成员 self.g ...
- 关于Android studio的安装和配置问题
一.Android studio的安装 我们可以从中文社区http://www.android-studio.org/下载Android studio最新版本,然后点击安装即可. 之后我们直接运行an ...
- Spring 事件
JDK事件 java通过java.util.EventObject类和java.util.EventListener接口描述事件和监听器 事件源,事件的产生者,任何一个EventObject都必须拥有 ...
- OneAPM大讲堂 | Metrics, Tracing 和 Logging 的关系
[编者按]这是在 OpenTracing 和分布式追踪领域内广受欢迎的一片博客文章.在构建监控系统时,大家往往在这几个名词和方式之间纠结. 通过这篇文章,作者很好的阐述了分布式追踪.统计指标与日志之间 ...
- 安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server log in Event Viewer for more details"错误.原因是启动"VisualSVN Server"失败
安装VisualSVN Server 报"Service 'VisualSVN Server' failed to start. Please check VisualSVN Server ...
- 在ASP.NET Core中使用多环境
原文地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.1#star ...
- Windows结构化异常处理浅析
近期一直被一个问题所困扰,就是写出来的程序老是出现无故崩溃,有的地方自己知道可能有问题,但是有的地方又根本没办法知道有什么问题.更苦逼的事情是,我们的程序是需要7x24服务客户,虽然不需要实时精准零差 ...
- Kibana中的Coordinate Map地图报索引错误的问题
今天做地图定位展示,展示的是ApacheWeb服务器的访问日志文件中的来源IP.但是中间出现了报错环节,说是索引不能匹配到geo_point类型,实在是不懂这是在说什么,后来在网站找了方法就解决了.主 ...