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.

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

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

Sample Input:

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

Sample Output:

LCA of 2 and 5 is 3.
8 is an ancestor of 7.
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<iostream>
#include<algorithm>
#include<cstdio>
#include<map>
using namespace std;
typedef struct NODE{
struct NODE* lchild, *rchild;
int data;
}node;
int M, N;
int pre[], in[];
map<int, int>mp;
node* create(int preL, int preR, int inL, int inR){
if(preL > preR)
return NULL;
node* root = new node;
root->data = pre[preL];
int mid;
for(int i = inL; i <= inR; i++){
if(in[i] == root->data){
mid = i;
break;
}
}
int len = mid - inL;
root->lchild = create(preL + , preL + len, inL, mid - );
root->rchild = create(preL + len + , preR, mid + , inR);
return root;
}
node* find(node* root, int u, int v){
if(root == NULL || root->data == u || root->data == v)
return root;
node* ll = find(root->lchild, u, v);
node* rr = find(root->rchild, u, v);
if(ll != NULL && rr != NULL){
return root;
}
if(ll != NULL){
return ll;
}
if(rr != NULL){
return rr;
}
}
int main(){
scanf("%d%d", &M, &N);
for(int i = ; i < N; i++){
scanf("%d", &in[i]);
pre[i] = in[i];
mp[pre[i]] = ;
}
sort(in, in + N);
node* root = create(, N - , , N - );
for(int i = ; i < M; i++){
int u, v;
scanf("%d%d", &u, &v);
if(mp.count(u) == && mp.count(v) == ){
printf("ERROR: %d and %d are not found.\n", u, v);
}else if(mp.count(u) == ){
printf("ERROR: %d is not found.\n",u );
}else if(mp.count(v) == ){
printf("ERROR: %d is not found.\n",v);
}else{
node* ans = find(root, u, v);
if(ans->data != u && ans->data != v){
printf("LCA of %d and %d is %d.\n", u, v, ans->data);
}else if(ans->data == u){
printf("%d is an ancestor of %d.\n", u, v);
}else{
printf("%d is an ancestor of %d.\n", v, u);
}
}
}
cin >> N;
return ;
}

总结:

1、题意:给出一个BST的先序序列,再给出两个点u、v,要求在BST中找出uv的最低公共祖先。

2、BST已知先序建树有两种方法,1)先序序列的顺序就是插入顺序,直接依次插入。2)对先序进行排序得到中序序列(BST的中序是从小到大的有序序列),由先序和中序进行递归建树。由于本题的N个数很大,使用insert方法会超时,尤其是在树高度为N时,复杂度为O(n^2)。所以最好采用先序+中序建树。

3、找最低的公共祖先。这种类型的任务一般采用后序递归遍历的办法:先处理左子树,再处理右子树,等左右子树都完成后,综合左右子树返回的信息与root的信息进行某些处理,再返回本层递归的结果。具体到本题,uv只有两种情况:1)即uv分别在某w节点的左右子树,则w为所求。2)uv本身就有祖先后代关系,则若u为祖先,u即为所求。

后序递归,若root为NULL或uv时,说明查找失败或成功,直接返回root。否则说明root为普通节点,先对root的左右子树分别查找。若左右子树都不空时,说明uv分别在root的左右两侧子树,则root即为所求。否则,说明uv在root的一侧子树,若在root的左侧,则将root左侧的查找结果返回。

A1143. Lowest Common Ancestor的更多相关文章

  1. PAT A1143 Lowest Common Ancestor (30 分)——二叉搜索树,lca

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

  2. PAT_A1143#Lowest Common Ancestor

    Source: PAT A1143 Lowest Common Ancestor (30 分) Description: The lowest common ancestor (LCA) of two ...

  3. [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  4. [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  5. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  6. [LeetCode]Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  7. 数据结构与算法(1)支线任务4——Lowest Common Ancestor of a Binary Tree

    题目如下:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, fin ...

  8. Lowest Common Ancestor of a Binary Search Tree

    Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...

  9. Lowest Common Ancestor of a Binary Tree

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

随机推荐

  1. pHP生成唯一单号

    这几天一直在写个人使用的用户中心,虽然期间遇到不少的问题,但还是一点点的都解决了,也从制作期间学到不少的知识,今天就说一说利用PHP生成订单单的方法. 订单号,大家都不陌生,无论从在网上购物,还是在线 ...

  2. 国内的go get问题的解决

    在国内采用go get有时会下载不到一些网站如golang.org的依赖包. 方法1(亲测有效): gopm 代替go 下载第三方依赖包可以采用gopm从golang.org一些镜像网站上下载. 注意 ...

  3. 在python中定义二维数组

    发表于 http://liamchzh.0fees.net/?p=234&i=1 一次偶然的机会,发现python中list非常有意思. 先看一段代码 [py]array = [0, 0, 0 ...

  4. WPF中关于对前台Xaml中Triggers的一些重要思考。

    今天在做一个小Demo的时候碰到了一个比较奇怪的问题,就是其中一个Trigger始终无法执行,<Trigger Property="Popup.IsOpen" Value=& ...

  5. 十分钟了结MySQL information_schema

    information_schema数据库是MySQL系统自带的数据库,它提供了数据库元数据的访问方式.感觉information_schema就像是MySQL实例的一个百科全书,记录了数据库当中大部 ...

  6. TestNG之使用ReportNG生成测试报告

    TestNG使用ReportNG生成测试报告会更加美观. 依赖包 <!--testNG报告依赖包--> <dependency> <groupId>org.test ...

  7. Lodop控件NewPage();测试输出空白页

    LODOP.NewPage();和LODOP.NewPageA();是强制分页语句,两者的区别可查看本博客的相关博文:Lodop强制分页LODOP.NewPage()和LODOP.NewPageA() ...

  8. Rest模式get,put,post,delete含义与区别

    POST   /uri     创建   DELETE /uri/xxx 删除    PUT    /uri/xxx 更新或创建   GET    /uri/xxx 查看   GET操作是安全的.所谓 ...

  9. import logging报错raise notimplementederror 'emit must be implemented ' ^

    在导入logging的时候出现这个错误 大概看了一下,就是因为python内置里面已经有logging这个模块,所以不需要再安装 在site-packages里面找到关于logging的文件,删掉 重 ...

  10. SpringBoot部署jar与war

    jar部署与启动/关闭 1.打包 clean 清理已有target目录 package 重新打包 获取打包路径,通过 scp命令发送到服务器端,scp -P ${port} ${.jar} ${use ...