PAT-A1151 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 and V as descendants.

Given any two nodes in a binary tree, you are supposed to find their LCA.

输入格式:
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.

输出格式:
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…

输入样例:
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

输出样例:
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.

题意:
给出一棵n个结点的二叉树的中序序列和先序序列,然后给出m个测试样例,每个测试样例包含两个结点,如果这两个结点都在这棵树中,寻找它们的最近的公共祖先,如果不满足,输出缺失了哪些结点。

思路:
1.比较麻烦的思路是先根据先序序列和中序序列建立一颗二叉树,然后找出两条从测试结点开始到根结点的路径,从根结点开始比较这两条路径并记录相同的结点,当遇到不同的结点后就跳出,便找到了LCA。
2.简洁的思路是参照了柳神的代码,不建树,根据根结点在先序和中序序列中的特性寻找LCA,判断测试结点是否在树中存在则根据建立的map,如果不存在,则值为0。
指路:
柳神博客中该题的解答

参考代码1:

#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1000010;
int m, n; //m:测试对数, n:结点数
int inSeq[maxn], preSeq[maxn]; //中序序列和先序序列
int root = -1; //根结点
 
struct node{
	int data;
	int lchild;
	int rchild;
	int father; 
}nd[maxn];

//根据中序序列和先序序列构建二叉树 
int createTree(int preL, int preR, int inL, int inR){
	if(preL > preR) return -1;
	int sep = -1; //左右分隔 
	int rt = preSeq[preL];
	nd[rt].data = rt;
	for(int i = inL; i <= inR; i++){
		if(rt == inSeq[i]){
			sep = i;
			break; 
		}
	}
	int numLeft = sep - inL; //左边的长度 
	nd[rt].lchild = createTree(preL+1, preL+numLeft, inL, sep-1);
	if(nd[rt].lchild != -1){
		nd[nd[rt].lchild].father = rt;
	}
	nd[rt].rchild = createTree(preL+numLeft+1, preR, sep+1, inR);
	if(nd[rt].rchild != -1){
		nd[nd[rt].rchild].father = rt;
	}
	return rt;
}

//初始化 
void init(){
	for(int i = 0; i < maxn; i++){
		nd[i].data = nd[i].lchild = nd[i].rchild = -1;
	}
} 

int findLCA(int u, int v){
	vector<int> seq1, seq2;
	while(u != -1){
		seq1.push_back(u);
		u = nd[u].father;
	}
	while(v != -1){
		seq2.push_back(v);
		v = nd[v].father;
	}
	reverse(seq1.begin(), seq1.end());
	reverse(seq2.begin(), seq2.end());
	int len1 = seq1.size();
	int len2 = seq2.size();
	int mLen = min(len1, len2);
	int LCA = root;
	for(int i = 0; i < mLen; i++){
		if(seq1[i] == seq2[i]){
			LCA = seq1[i];
		}else{
			break;
		}
	}
	return LCA;
}

int main(){
	init();
	scanf("%d%d", &m, &n);
	for(int i = 0; i < n; i++){
		scanf("%d", &inSeq[i]);
	}
	for(int i = 0; i < n; i++){
		scanf("%d", &preSeq[i]);
	}
	root = createTree(0, n-1, 0, n-1);
	nd[root].father = -1;
	for(int i = 0; i < m; i++){
		int u, v;
		scanf("%d%d", &u, &v);
		if(u > 0 && nd[u].data != -1){
			if(v > 0 && nd[v].data != -1){ //u和v都存在 
				int LCA = findLCA(u, v);
				if(LCA == u){
					printf("%d is an ancestor of %d.\n", u, v);
				}else if(LCA == v){
					printf("%d is an ancestor of %d.\n", v, u);
				}else{
					printf("LCA of %d and %d is %d.\n", u, v, LCA);
				}
			}else{ //v不存在 
				printf("ERROR: %d is not found.\n", v);
			}
		}else{
			if(v > 0 && nd[v].data != -1){ //u不存在 
				printf("ERROR: %d is not found.\n", u);
			}else{ //u和v都不存在 
				printf("ERROR: %d and %d are not found.\n", u, v);
			}
		}
	}
	return 0;
}

参考代码2:

//1151 LCA in a Binary Tree (30分)
#include <stdio.h>
#include <vector>
#include <map>
using namespace std; 
int m, n; //m:被测试数量,n:结点数 
vector<int> inSeq, preSeq;
map<int, int> pos; //便于查找某个数在中序序列中位置 

void findLCA(int inL, int inR, int preRoot, int u, int v){
	if(inL > inR) return;
	int inRoot = pos[preSeq[preRoot]];
	if((pos[u] < inRoot && pos[v] > inRoot) || (pos[v] < inRoot && pos[u] > inRoot)){
		printf("LCA of %d and %d is %d.\n", u, v, preSeq[preRoot]);
	}else if(pos[u] == inRoot){
		printf("%d is an ancestor of %d.\n", u, v);
	}else if(pos[v] == inRoot){
		printf("%d is an ancestor of %d.\n", v, u);
	}else if(pos[u] < inRoot && pos[v] < inRoot){
		findLCA(inL, inRoot-1, preRoot+1, u, v);
	}else if(pos[u] > inRoot && pos[v] > inRoot){
		findLCA(inRoot+1, inR, preRoot+1+inRoot-inL, u, v);
	}
}

int main(){
	scanf("%d%d", &m, &n);
	inSeq.resize(n+1); //数组只需要n+1大小 
	preSeq.resize(n+1);
	for(int i = 1; i <= n; i++){
		scanf("%d", &inSeq[i]);
		pos[inSeq[i]] = i;
	} 
	for(int i = 1; i <= n; i++){
		scanf("%d", &preSeq[i]);
	}
	for(int i = 1; i <= m; i++){
		int u, v;
		scanf("%d%d", &u, &v);
		if(pos[u] == 0 && pos[v] == 0){
			printf("ERROR: %d and %d are not found.\n", u, v);
		}else if(pos[u] == 0 || pos[v] == 0){
			printf("ERROR: %d is not found.\n", pos[u] == 0 ? u : v);
		}else{
			findLCA(1, n, 1, u, v);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值