【PAT】1143 Lowest Common Ancestor(测试点分析,普通思想,建树利用排序树的特点找公共祖先)

31 篇文章 2 订阅
14 篇文章 0 订阅

【PAT】1143 Lowest Common Ancestor

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 (<= 1000), the number of pairs of nodes to be tested; and N (<= 10000), 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.

我的思想(绝大部分人的第一种思想)

1、利用前序遍历序列和中序遍历序列进行建树。其中中序遍历就是前序遍历的从小到大的排序(排序树的特点)。
2、然后开始前序遍历(假设需要找u,v两点的祖先)可以分为下面几个情况
①、u和v在root的两侧,也就是一个大于root一个小于root那么root就是他们的共同祖先。
②、若u,v都小于root那么进行遍历root的左子树,反之遍历其右子树。
③、将找到的key和原始的u,v进行比较,从而得出输出的情况。

注意:我们需要注意Key的取址范围是int 也就是 (1>>32,1<<31-1),所以大家可以考虑使用unordered_map,否则可能存在测试点段错误

AC代码:

#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
struct BNode {	
	int left, right;
};
unordered_map<int,BNode> BSTree;
unordered_map<int, bool>visited;
int pre[10007], in[10007];
int M, N;
int Build_Tree(int l1,int h1,int l2,int h2) {
	if (l1 > h1) return 0;
	int root = pre[l1];
	int m = l2;
	while (in[m] != root) m++;
	int len = m - l2;
	BSTree[root].left = Build_Tree(l1+1,l1+len,l2,m-1);
	BSTree[root].right = Build_Tree(l1+len+1,h1, m + 1, h2);
	return root;
}
int preOrder(int root,int a,int b) {
	if (root == 0) return 0;
	if ((a <= root && b >= root) || (a >= root && b <= root)) return root;
	if(a<root&&b<root)//a,b都在左子树上
		return preOrder(BSTree[root].left,a,b);
	if(a>root&&b>root)//a,b都在右子树上
		return preOrder(BSTree[root].right,a,b);
}
int main() {
	for (int i = 0; i < N; i++) {
		int temp; scanf("%d", &temp);
		pre[i] = in[i] = temp;
		visited[temp] = true;
	}
	sort(in, in + N);
	Build_Tree(0, N - 1, 0, N - 1);
	for (int i = 0; i < M; i++) {
		int a, b; scanf("%d %d", &a, &b);
		if (visited[a] == false && visited[b] == false)
		{printf("ERROR: %d and %d are not found.\n", a, b); continue;}
		if (visited[a] == false && visited[b] == true)
		{printf("ERROR: %d is not found.\n",a); continue;}
		if (visited[a] == true && visited[b] == false)
		{printf("ERROR: %d is not found.\n",b); continue; }
		int ansc = preOrder(pre[0], a, b);
		if (ansc == a) printf("%d is an ancestor of %d.\n",a,b);
		else if (ansc == b) printf("%d is an ancestor of %d.\n", b, a);
		else printf("LCA of %d and %d is %d.\n", a, b, ansc);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是用C++编写的算法,它使用了递归的方法,在二叉排序出任意两个不同节点的最近公共祖先: ```cpp #include <iostream> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; }; TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root) return NULL; // 如果根节点为空,返回NULL if (root->val > p->val && root->val > q->val) { return lowestCommonAncestor(root->left, p, q); // 如果根节点大于p和q的值,那么p和q在根节点的左子中,递归左子 } else if (root->val < p->val && root->val < q->val) { return lowestCommonAncestor(root->right, p, q); // 如果根节点小于p和q的值,那么p和q在根节点的右子中,递归右子 } else { return root; // 如果根节点的值介于p和q的值之间,那么根节点就是它们的最近公共祖先 } } int main() { TreeNode* root = new TreeNode{6, NULL, NULL}; root->left = new TreeNode{2, NULL, NULL}; root->right = new TreeNode{8, NULL, NULL}; root->left->left = new TreeNode{0, NULL, NULL}; root->left->right = new TreeNode{4, NULL, NULL}; root->left->right->left = new TreeNode{3, NULL, NULL}; root->left->right->right = new TreeNode{5, NULL, NULL}; root->right->left = new TreeNode{7, NULL, NULL}; root->right->right = new TreeNode{9, NULL, NULL}; TreeNode* p = root->left->right->left; TreeNode* q = root->left->right->right; TreeNode* lca = lowestCommonAncestor(root, p, q); cout << "Lowest Common Ancestor of " << p->val << " and " << q->val << " is " << lca->val << endl; return 0; } ``` 该程序的输出结果是: ``` Lowest Common Ancestor of 3 and 5 is 4 ``` 其中,root是二叉排序的根节点,p和q是任意两个不同的节点,lca是它们的最近公共祖先

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值