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); 
	
}
发布了47 篇原创文章 · 获赞 12 · 访问量 7245

猜你喜欢

转载自blog.csdn.net/weixin_43717681/article/details/89429935
今日推荐