6-3 二叉搜索树中的最近公共祖先 (25分)
在一棵树T中两个结点u和v的最近公共祖先(LCA),是树中以u和v为其后代的深度最大的那个结点。现给定某二叉搜索树(BST)中任意两个结点,要求你找出它们的最近公共祖先。
函数接口定义:
int LCA( Tree T, int u, int v );
其中Tree的定义如下:
typedef struct TreeNode *Tree;
struct TreeNode {
int Key;
Tree Left;
Tree Right;
};
函数LCA须返回树T中两个结点u和v的最近公共祖先结点的键值。若u或v不在树中,则应返回ERROR。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef struct TreeNode Tree;
struct TreeNode {
int Key;
Tree Left;
Tree Right;
};
Tree BuildTree(); / 细节在此不表 /
int LCA( Tree T, int u, int v );
int main()
{
Tree T;
int u, v, ans;
T = BuildTree();
scanf("%d %d", &u, &v);
ans = LCA(T, u, v);
if ( ans == ERROR ) printf(“Wrong input\n”);
else printf(“LCA = %d\n”, ans);
return 0;
}
/ 你的代码将被嵌在这里 */
输入样例1 (对于下图给定的树):
2 7
输出样例1:
LCA = 6
输入样例2 (对于例1中的树):
1 9
输出样例2:
Wrong input
int LCA(Tree T, int u, int v)
{
if (v < u) {
int temp;
temp = v;
v = u;
u = temp;
}
while (T) {
if (T->Key >= u && T->Key <= v)
break;
if (T->Key <= u && T->Key <= v)
T = T->Right;
else if (T->Key >= u && T->Key >= v)
T = T->Left;
}
Tree temp1 = T;
Tree temp2 = T;
while (temp1&&temp2) {
if (temp1->Key == u && temp2->Key == v)
return T->Key;
if (u < temp1->Key)
temp1 = temp1->Left;
else if (u > temp1->Key)
temp1 = temp1->Right;
if (v < temp2->Key)
temp2 = temp2->Left;
else if (v > temp2->Key)
temp2 = temp2->Right;
}
return ERROR;
}