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

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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值