大一下半期数据结构
二叉搜索树中的最近公共祖先
在一棵树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;
}
/* 你的代码将被嵌在这里 */
题目解答:
int find(Tree T,int u)
{
if(!T)
return 0;
if(T->Key==u)
return 1;
if(T->Key<u)
return find(T->Right,u);
if(T->Key>u)
return find(T->Left,u);
}
int LCA( Tree T, int u, int v )
{
if(!T)
return ERROR;
if(!find(T,u)||!find(T,v))
return ERROR;
if(u==T->Key||v==T->Key)
return T->Key;
if(u<T->Key&&v>T->Key||u>T->Key&&v<T->Key)
return T->Key;
if(u>T->Key)
return LCA(T->Right,u,v);
if(u<T->Key)
return LCA(T->Left,u,v);
}