Skip to content

Commit cedde52

Browse files
committed
Create problem24
1 parent b6b03aa commit cedde52

File tree

1 file changed

+129
-0
lines changed

1 file changed

+129
-0
lines changed

problem24

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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+
Expected Output:
124+
125+
LCA of 10 and 14 is 12
126+
127+
LCA of 14 and 8 is 8
128+
129+
LCA of 10 and 22 is 20

0 commit comments

Comments
 (0)