-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcabst.cpp
59 lines (51 loc) · 1.56 KB
/
lcabst.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// A recursive C program to find LCA of two nodes n1 and n2.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left, *right;
};
/* Function to find LCA of n1 and n2. The function assumes that both
n1 and n2 are present in BST */
struct node *lca(struct node* root, int n1, int n2)
{
if(root == NULL)
return NULL;
if(root->data > n1 && root->data > n2)
return lca(root->left, n1, n2);
if(root->data < n1 && root->data < n2)
return lca(root->right, n1, n2);
return root;
}
/* Helper function that allocates a new node with the given data.*/
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
/* Driver program to test lca() */
int main()
{
// Let us construct the BST shown in the above figure
struct node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
int n1 = 10, n2 = 14;
struct node *t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 14, n2 = 8;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 10, n2 = 22;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
getchar();
return 0;
}