进阶实验8-2.3 二叉搜索树的最近公共祖先 (30分)
Posted 8023spz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了进阶实验8-2.3 二叉搜索树的最近公共祖先 (30分)相关的知识,希望对你有一定的参考价值。
给定一棵二叉搜索树的先序遍历序列,要求你找出任意两结点的最近公共祖先结点(简称 LCA)。
输入格式:
输入的第一行给出两个正整数:待查询的结点对数 M(≤ 1 000)和二叉搜索树中结点个数 N(≤ 10 000)。随后一行给出 N 个不同的整数,为二叉搜索树的先序遍历序列。最后 M 行,每行给出一对整数键值 U 和 V。所有键值都在整型int范围内。
输出格式:
对每一对给定的 U 和 V,如果找到 A
是它们的最近公共祖先结点的键值,则在一行中输出 LCA of U and V is A.
。但如果 U 和 V 中的一个结点是另一个结点的祖先,则在一行中输出 X is an ancestor of Y.
,其中 X
是那个祖先结点的键值,Y
是另一个键值。如果 二叉搜索树中找不到以 U 或 V 为键值的结点,则输出 ERROR: U is not found.
或者 ERROR: V is not found.
,或者 ERROR: U and V are not found.
。
输入样例:
6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
输出样例:
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 <cstdio> #include <algorithm> #include <map> using namespace std; struct tree { int Data,Height; tree *Last,*Left,*Right; }*head; int q[10001],z[10001],m,n; map<int,tree *> mp; tree *createNode(int d,int h) { tree *p = new tree(); p -> Data = d; mp[d] = p; p -> Height = h; p -> Last = p -> Left = p -> Right = NULL; return p; } tree *createTree(int ql,int qr,int zl,int zr,int h) { tree *p = createNode(q[ql],h); for(int i = zl;i <= zr;i ++) { if(z[i] == q[ql]) { if(i > zl)p -> Left = createTree(ql + 1,ql + i - zl,zl,i - 1,h + 1),p -> Left -> Last = p; if(i < zr)p -> Right = createTree(ql + i - zl + 1,qr,i + 1,zr,h + 1),p -> Right -> Last = p; break; } } return p; } tree *createTre(int l,int r,int h) { tree *p = createNode(q[l],h); for(int i = l + 1;i <= r + 1;i ++) { if(i == r + 1 || q[i] >= q[l]) { if(i > l + 1)p -> Left = createTre(l + 1,i - 1,h + 1),p -> Left -> Last = p; if(r >= i)p -> Right = createTre(i,r,h + 1),p -> Right -> Last = p; return p; } } } void check(int a,int b) { if(mp[a] == NULL && mp[b] == NULL)printf("ERROR: %d and %d are not found. ",a,b); else if(mp[a] == NULL)printf("ERROR: %d is not found. ",a); else if(mp[b] == NULL)printf("ERROR: %d is not found. ",b); else { tree *t1 = mp[a],*t2 = mp[b]; while(t1 -> Height != t2 -> Height) { if(t1 -> Height > t2 -> Height)t1 = t1 -> Last; else t2 = t2 -> Last; } if(t1 == t2) { printf("%d is an ancestor of %d. ",t1 -> Data,a == t1 -> Data ? b : a); return; } t1 = t1 -> Last; t2 = t2 -> Last; while(t1 != t2) { t1 = t1 -> Last; t2 = t2 -> Last; } printf("LCA of %d and %d is %d. ",a,b,t1 -> Data); } } int main() { int a,b; scanf("%d%d",&m,&n); for(int i = 0;i < n;i ++) { scanf("%d",&q[i]); } head = createTre(0,n - 1,0); for(int i = 0;i < m;i ++) { scanf("%d%d",&a,&b); check(a,b); } }
以上是关于进阶实验8-2.3 二叉搜索树的最近公共祖先 (30分)的主要内容,如果未能解决你的问题,请参考以下文章