1151 LCA in a Binary Tree (30point(s))
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 X
is 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.
题意:
根据先序遍历和中序遍历的结果,构建一棵二叉树,然后,在这颗二叉树中查找两个结点的最近公共祖先节点。
思路:
题目可以分成两部分组成
1. 先根据前序和中序构建一棵二叉树。
构建二叉树的时候采用递归的方式进行构建,根节点root在preorder中进行查找,再根据root在inorder中的位置确定左右子树中的节点个数。左子树的根节点就是其父节点root在preorder中的下标tag+1,右子树的根节点为tag + pos + 1,(pos为root在inorder中的下标)。递归跳出的条件是 start > end || tag >= inorder.size()。
2. 在在二叉树中查找两个结点的公共祖先节点。
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/comments/
Code:
#include<iostream>
#include<vector>
#include<set> using namespace std; typedef struct Node* node; struct Node {
int val;
node left;
node right; Node() {
val = 0;
left = NULL;
right = NULL;
} Node(int v) {
val = v;
left = NULL;
right = NULL;
}
}; vector<int> inorder, preorder;
int tag = 0; node buildTree(int start, int end, int tag) {
if (start >= end || tag >= inorder.size()) return NULL;
int val = preorder[tag];
node root = new Node(val);
int lend, rstart, pos;
for (int i = 0; i < inorder.size(); ++i) {
if (inorder[i] == val) {
pos = i;
break;
}
}
lend = pos - 1;
rstart = pos + 1;
root->left = buildTree(start, lend, tag+1);
root->right = buildTree(rstart, end, tag+pos+1);
return root;
} node lowestCommonAncestor(node root, int n1, int n2) {
if (!root || root->val == n1 || root->val == n2) return root;
node left = lowestCommonAncestor(root->left, n1, n2);
node right = lowestCommonAncestor(root->right, n1, n2);
return !left ? right : !right ? left : root;
} int main() {
int m, n, t;
cin >> m >> n; set<int> s;
for (int i = 0; i < n; ++i) {
cin >> t;
inorder.push_back(t);
s.insert(t);
}
for (int i = 0; i < n; ++i) {
cin >> t;
preorder.push_back(t);
} node root = buildTree(0, n-1, 0); for (int i = 0; i < m; ++i) {
int n1, n2;
cin >> n1 >> n2;
if (s.find(n1) != s.end() && s.find(n2) != s.end()) {
node lca = lowestCommonAncestor(root, n1, n2);
int v = lca->val;
if (v == n1) {
cout << n1 << " is an ancestor of " << n2 << "." << endl;
} else if (v == n2) {
cout << n2 << " is an ancestor of " << n1 << "." << endl;
} else {
cout << "LCA of " << n1 << " and " << n2 << " is " << v << "." << endl;
}
} else if (s.find(n1) != s.end()) {
cout << "ERROR: " << n2 << " is not found." << endl;
} else if (s.find(n2) != s.end()) {
cout << "ERROR: " << n1 << " is not found." << endl;
} else {
cout << "ERROR: " << n1 << " and " << n2 << " are not found." << endl;
} } return 0;
}
最后还是有一组数据没有通过。
建树的时候一定要注意小标的问题。
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 typedef struct Node* node;
6
7 struct Node {
8 int val;
9 node left;
10 node right;
11 Node(int v) {
12 val = v;
13 left = NULL;
14 right = NULL;
15 }
16 };
17
18 vector<int> inOrder, preOrder;
19
20 node buildTree(int inl, int inr, int prel, int prer) {
21 // cout << prel << " " << prer << endl;
22 if (prel > prer || inl > inr) return NULL;
23 node root = new Node(preOrder[prel]);
24 int pos = 0;
25 for (int i = inl; i <= inr; ++i) {
26 if (inOrder[i] == preOrder[prel]) {
27 pos = i;
28 break;
29 }
30 }
31 int leftLen = pos - inl;
32 // cout << rightLen << " " << leftLen << endl;
33 root->left = buildTree(inl, pos - 1, prel + 1, prel + leftLen);
34 root->right = buildTree(pos + 1, inr, prel + leftLen + 1, prer);
35 return root;
36 }
37
38 node LCA(node root, int u, int v) {
39 if (!root || root->val == u || root->val == v) return root;
40 node left = LCA(root->left, u, v);
41 node right = LCA(root->right, u, v);
42 return !left ? right : !right ? left : root;
43 }
44
45 int main() {
46 int m, n;
47 cin >> m >> n;
48 inOrder.resize(n);
49 preOrder.resize(n);
50 for (int i = 0; i < n; ++i) cin >> inOrder[i];
51 for (int i = 0; i < n; ++i) cin >> preOrder[i];
52 set<int> visited(inOrder.begin(), inOrder.end());
53 node root = buildTree(0, n - 1, 0, n - 1);
54 int u, v;
55 for (int i = 0; i < m; ++i) {
56 cin >> u >> v;
57 if (visited.find(u) != visited.end() &&
58 visited.find(v) != visited.end()) {
59 node lca = LCA(root, u, v);
60 if (lca->val == u)
61 cout << u << " is an ancestor of " << v << "." << endl;
62 else if (lca->val == v)
63 cout << v << " is an ancestor of " << u << "." << endl;
64 else
65 cout << "LCA of " << u << " and " << v << " is " << lca->val
66 << "." << endl;
67 } else if (visited.find(u) != visited.end()) {
68 cout << "ERROR: " << v << " is not found." << endl;
69 } else if (visited.find(v) != visited.end()) {
70 cout << "ERROR: " << u << " is not found." << endl;
71 } else {
72 cout << "ERROR: " << u << " and " << v << " are not found." << endl;
73 }
74 }
75
76 return 0;
77 }
不用建树的代码:
1 #include <iostream>
2 #include <vector>
3 #include <map>
4 using namespace std;
5 map<int, int> pos;
6 vector<int> in, pre;
7 void lca(int inl, int inr, int preRoot, int a, int b) {
8 if (inl > inr) return;
9 int inRoot = pos[pre[preRoot]], aIn = pos[a], bIn = pos[b];
10 if (aIn < inRoot && bIn < inRoot)
11 lca(inl, inRoot-1, preRoot+1, a, b);
12 else if ((aIn < inRoot && bIn > inRoot) || (aIn > inRoot && bIn < inRoot))
13 printf("LCA of %d and %d is %d.\n", a, b, in[inRoot]);
14 else if (aIn > inRoot && bIn > inRoot)
15 lca(inRoot+1, inr, preRoot+1+(inRoot-inl), a, b);
16 else if (aIn == inRoot)
17 printf("%d is an ancestor of %d.\n", a, b);
18 else if (bIn == inRoot)
19 printf("%d is an ancestor of %d.\n", b, a);
20 }
21 int main() {
22 int m, n, a, b;
23 scanf("%d %d", &m, &n);
24 in.resize(n + 1), pre.resize(n + 1);
25 for (int i = 1; i <= n; i++) {
26 scanf("%d", &in[i]);
27 pos[in[i]] = i;
28 }
29 for (int i = 1; i <= n; i++) scanf("%d", &pre[i]);
30 for (int i = 0; i < m; i++) {
31 scanf("%d %d", &a, &b);
32 if (pos[a] == 0 && pos[b] == 0)
33 printf("ERROR: %d and %d are not found.\n", a, b);
34 else if (pos[a] == 0 || pos[b] == 0)
35 printf("ERROR: %d is not found.\n", pos[a] == 0 ? a : b);
36 else
37 lca(1, n, 1, a, b);
38 }
39 return 0;
40 }
1151 LCA in a Binary Tree (30point(s))的更多相关文章
- 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 ...
- 【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
https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856 The lowest common anc ...
- 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 both U ...
- 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 ...
- 1151 LCA in a Binary Tree
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...
- PAT甲级|1151 LCA in a Binary Tree 先序中序遍历建树 lca
给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近 ...
- 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)+最近公共祖先+二叉树的中序遍历和前序遍历
LCA in a Binary Tree PAT-1151 本题的困难在于如何在中序遍历和前序遍历已知的情况下找出两个结点的最近公共祖先. 可以利用据中序遍历和前序遍历构建树的思路,判断两个结点在根节 ...
随机推荐
- Prism.WPF -- Prism框架使用(上)
本文参考Prism官方示例 创建Prism项目 将App.xaml中的WPF标准Application替换为PrismApplication,移除StartupUri属性: 将App.xaml.cs中 ...
- C#语言特性及发展史
本文按照C#语言的发展历史,介绍C#每个版本的新增特性,主要参考微软官方文档.了解这些语言特性可以帮助我们更高效的编写C#代码. C# 1.0 与Visual Studio .NET 2002一起发布 ...
- 后端程序员之路 23、一个c++的api framework
在"21.一个cgi的c++封装"中,我们封装了cgi,在这之上,我们可以再来封装一个webapi的framework.当然,前文的Casablanca是个不错的选择,但是它比较庞 ...
- Linux 切换 shell
查看当前已安装的shell [root@CentOSv64 my]# cat /etc/shells /bin/sh /bin/bash /sbin/nologin /bin/dash /bin/tc ...
- 500GJava/Hadoop/Spark/机器学习...视频教程免费分享 百度云持续更新
参加工作这么长时间了,工作中遇到了不少技能都是看视频教程学习的,相比较看书而言看视频确实比较容易理解.分享一下自己看过的和收集的视频教程. 资源包括: 大数据方面的Hadoop(云帆,小象学院,八斗学 ...
- 不用代码趣讲 ZooKeeper 集群
本文作者:HelloGitHub-老荀 Hi,这里是 HelloGitHub 推出的 HelloZooKeeper 系列,免费开源.有趣.入门级的 ZooKeeper 教程,面向有编程基础的新手. 项 ...
- 【Arduino学习笔记07】模拟信号的输入与输出 analogRead() analogWrite() map() constrain()
模拟信号:Arduino中的模拟信号就是0v~5v的连续的电压值 数字信号:Arduino中的数字信号就是高电平(5V)或者低电平(0V),是两个离散的值 模拟信号->数字信号:ADC(模数转换 ...
- Elasticsearch 模块 - Shard Allocation 机制
原文 1. 背景 shard allocation 意思是分片分配, 是一个将分片分配到节点的过程; 可能发生该操作的过程包括: 初始恢复(initial recovery) 副本分配(replica ...
- java将一个list转换成一个String,中间用分隔符隔开
List sn=[123,1231,1231,231] sn.toString();//[123,1231,1231,231] sn.join(',').toString();//123,1231,1 ...
- MyBatis(二):自定义持久层框架思路分析
使用端 引入架构端Maven依赖 SqlMapConfig.xml-数据库配置信息(数据库连接jar名称.连接URL.用户名.密码),引入Mapper.xml的路径 XxMapper.xml-SQL配 ...