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;
}