|
| 1 | +//Solution by Pavithra B, 111712205071, IT dept. |
| 2 | + |
| 3 | +/* c code to find closest anchestor of two nodes */ |
| 4 | +#include <stdio.h> |
| 5 | +#include <stdlib.h> |
| 6 | + |
| 7 | +struct node |
| 8 | +{ |
| 9 | + int data; |
| 10 | + struct node* left, *right; |
| 11 | +}; |
| 12 | + |
| 13 | +/* Function to find LCA of n1 and n2. The function assumes that both |
| 14 | + n1 and n2 are present in BST */ |
| 15 | +struct node *lca(struct node* root, int n1, int n2) |
| 16 | +{ |
| 17 | + if (root == NULL) return NULL; |
| 18 | + |
| 19 | + // If both n1 and n2 are smaller than root, then LCA lies in left |
| 20 | + if (root->data > n1 && root->data > n2) |
| 21 | + return lca(root->left, n1, n2); |
| 22 | + |
| 23 | + // If both n1 and n2 are greater than root, then LCA lies in right |
| 24 | + if (root->data < n1 && root->data < n2) |
| 25 | + return lca(root->right, n1, n2); |
| 26 | + |
| 27 | + return root; |
| 28 | +} |
| 29 | + |
| 30 | +/* function that allocates a new node with the given data.*/ |
| 31 | +struct node* newNode(int data) |
| 32 | +{ |
| 33 | + struct node* node = (struct node*)malloc(sizeof(struct node)); |
| 34 | + node->data = data; |
| 35 | + node->left = node->right = NULL; |
| 36 | + return(node); |
| 37 | +} |
| 38 | + |
| 39 | +/* code to test */ |
| 40 | +int main() |
| 41 | +{ |
| 42 | + // Let us construct the BST shown in the above figure |
| 43 | + struct node *root = newNode(20); |
| 44 | + root->left = newNode(8); |
| 45 | + root->right = newNode(22); |
| 46 | + root->left->left = newNode(4); |
| 47 | + root->left->right = newNode(12); |
| 48 | + root->left->right->left = newNode(10); |
| 49 | + root->left->right->right = newNode(14); |
| 50 | + |
| 51 | + int n1 = 10, n2 = 14; |
| 52 | + struct node *t = lca(root, n1, n2); |
| 53 | + printf("LCA of %d and %d is %d \n", n1, n2, t->data); |
| 54 | + |
| 55 | + n1 = 14, n2 = 8; |
| 56 | + t = lca(root, n1, n2); |
| 57 | + printf("LCA of %d and %d is %d \n", n1, n2, t->data); |
| 58 | + |
| 59 | + n1 = 10, n2 = 22; |
| 60 | + t = lca(root, n1, n2); |
| 61 | + printf("LCA of %d and %d is %d \n", n1, n2, t->data); |
| 62 | + |
| 63 | + getchar(); |
| 64 | + return 0; |
| 65 | +} |
0 commit comments