Skip to content

Commit 4138085

Browse files
committed
Update problem24.c
1 parent 5536d06 commit 4138085

File tree

1 file changed

+123
-0
lines changed

1 file changed

+123
-0
lines changed

problem24.c

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,126 @@
1+
/By Manigandan, ECE
2+
3+
#include<stdio.h>
4+
5+
#include<stdlib.h>
6+
7+
struct node
8+
9+
{
10+
11+
int data;
12+
13+
struct node* left, *right;
14+
15+
};
16+
17+
18+
19+
struct node *lca(struct node* root, int n1, int n2)
20+
21+
{
22+
23+
if (root == NULL) return NULL;
24+
25+
26+
27+
// If both n1 and n2 are smaller than root, then LCA lies in left
28+
29+
if (root->data > n1 && root->data > n2)
30+
31+
return lca(root->left, n1, n2);
32+
33+
34+
35+
// If both n1 and n2 are greater than root, then LCA lies in right
36+
37+
if (root->data < n1 && root->data < n2)
38+
39+
return lca(root->right, n1, n2);
40+
41+
42+
43+
return root;
44+
45+
}
46+
47+
48+
49+
/* Helper function that allocates a new node with the given data.*/
50+
51+
struct node* newNode(int data)
52+
53+
{
54+
55+
struct node* node = (struct node*)malloc(sizeof(struct node));
56+
57+
node->data = data;
58+
59+
node->left = node->right = NULL;
60+
61+
return(node);
62+
63+
}
64+
65+
66+
67+
Program to check the same
68+
69+
Consider the binary tree shown
70+
71+
int main()
72+
73+
{
74+
75+
// Let us construct the BST shown in the above figure
76+
77+
struct node *root = newNode(20);
78+
79+
root->left = newNode(8);
80+
81+
root->right = newNode(22);
82+
83+
root->left->left = newNode(4);
84+
85+
root->left->right = newNode(12);
86+
87+
root->left->right->left = newNode(10);
88+
89+
root->left->right->right = newNode(14);
90+
91+
92+
93+
int n1 = 10, n2 = 14;
94+
95+
struct node *t = lca(root, n1, n2);
96+
97+
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
98+
99+
100+
101+
n1 = 14, n2 = 8;
102+
103+
t = lca(root, n1, n2);
104+
105+
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
106+
107+
108+
109+
n1 = 10, n2 = 22;
110+
111+
t = lca(root, n1, n2);
112+
113+
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
114+
115+
116+
117+
getchar();
118+
119+
return 0;
120+
121+
}
122+
123+
1124
//Solution by Pavithra B, 111712205071, IT dept.
2125

3126
/* c code to find closest anchestor of two nodes */

0 commit comments

Comments
 (0)