6-2 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 flag1=0,flag2=0;
int LCA( Tree T,  int u, int v ){
    if(!T)
        return ERROR;
    if(u>v){
        int temp;
        temp=u;
        u=v;
        v=temp;
    }
    if(u<=T->Key&&v>=T->Key){
        Tree t1=T,t2=T;
        while (t1) {
            if(t1->Key==u){
                flag1=1;
                break;
            }
            else if(t1->Key>u)
                t1=t1->Left;
            else if(t1->Key<u)
                t1=t1->Right;
        }
        while (t2) {
            if (t2->Key==v){
                flag2=1;
                break;
            }
            else if(t2->Key>v)
                t2=t2->Left;
            else if(t1->Key<v)
                t2=t2->Right;
        }
        if(flag1==1&&flag2==1)
            return T->Key;
        else
            return ERROR;
    }
    if(v<T->Key)
        return LCA(T->Left,u,v);
    if(u>T->Key)
        return LCA(T->Right,u,v);
    return ERROR;
}

猜你喜欢

转载自blog.csdn.net/qq_40215528/article/details/84939671