LCA in BST

 LCA in BST (25 分)

The lowest common ancestor (LCA) of two nodes u and v in a tree T is the deepest node that has both u and v as descendants. Given any two nodes in a binary search tree (BST), you are supposed to find their LCA.

Format of function:

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

where Tree is defined as the following:

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

The function LCA is supposed to return the key value of the LCA of u and v in T. In case that either u or v is not found in T, return ERROR instead.

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

#define ERROR -1
typedef struct TreeNode *Tree;
struct TreeNode {
    int   Key;
    Tree  Left;
    Tree  Right;
};

Tree BuildTree(); /* details omitted */
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;
}

/* Your function will be put here */

Sample Input 1 (for the tree shown in the Figure):

2 7

Sample Output 1:

LCA = 6

Sample Input 2 (for the same tree in Sample 1):

1 9

Sample Output 2:

Wrong input

int LCA(Tree T, int u, int v) {
    Tree myT = T, myT2 = T;
    Tree tu = NULL, tv = NULL;
    int temp = 0;
    if (u > v) { temp = u; u = v; v = temp; }
    while (myT != NULL) {
        if (myT->Key == u){ tu = myT; break; }
        else if (myT->Key > u) myT = myT->Left;
        else myT = myT->Right;
    }
    while (myT2 != NULL) {
        if (myT2->Key == v) { tv = myT2; break; }
        else if (myT2->Key > v) myT2 = myT2->Left;
        else myT2 = myT2->Right;
    }
    if (tv == NULL || tu == NULL) return ERROR;
    while (T != NULL) {
        if (v > T->Key&&u > T->Key) T = T->Right;
        else if (v < T->Key&&u < T->Key) T = T->Left;
        else if (u <= T->Key&&v >= T->Key) break;
    }
    if(T!=NULL)
    return T->Key;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值