6-3 二叉搜索树中的最近公共祖先 (25 分)

大一下半期数据结构

二叉搜索树中的最近公共祖先

 

在一棵树T中两个结点uv的最近公共祖先(LCA),是树中以uv为其后代的深度最大的那个结点。现给定某二叉搜索树(BST)中任意两个结点,要求你找出它们的最近公共祖先。

函数接口定义:

int LCA( Tree T, int u, int v );

其中Tree的定义如下:

typedef struct TreeNode *Tree;
struct TreeNode {
    int   Key;
    Tree  Left;
    Tree  Right;
};

函数LCA须返回树T中两个结点uv的最近公共祖先结点的键值。若uv不在树中,则应返回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); 
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值