-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASSG2_B190513CS_HADIF_6.c
114 lines (105 loc) · 2.17 KB
/
ASSG2_B190513CS_HADIF_6.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <stdlib.h>
typedef struct bNode{
int key;
struct bNode *left, *right, *p;
} *node;
typedef struct bst{
node root;
} *tree;
node createNode(int);
void insert(tree, node);
node search(tree, int);
int maxPath(tree, int, int);
int tmax(node, int);
int main()
{
tree T = (tree)malloc(sizeof(tree));
T->root = NULL;
int a, b;
char c;
do
{
scanf("%d%c", &a, &c);
insert(T, createNode(a));
} while (c!='\n');
scanf("%d%d", &a, &b);
printf("%d\n", maxPath(T, a, b));
return 0;
}
int tmax(node x, int a)
{
node t = x;
int max = t->key;
while(t->key!=a)
{
if(t->key<a)
t = t->right;
else if(t->key>a)
t = t->left;
max = (t->key>max && t->key!=a) ? t->key : max;
}
return max;
}
int maxPath(tree T, int a, int b)
{
node t = T->root;
int mx = 0;
while((a<t->key && b<t->key) || (a>t->key && b>t->key))
{
if(a<t->key && b<t->key)
t = t->left;
else if(a>t->key && b>t->key)
t = t->right;
}
if(t->key==a || t->key==b)
{
if((t->left && (t->left->key==a || t->left->key==b)) || (t->right && (t->right->key==a || t->right->key==b)))
return -1000001;
if(a<t->key || b<t->key)
mx = a<b ? tmax(t->left, a) : tmax(t->left, b);
else if(a>t->key || b>t->key)
mx = a>b ? tmax(t->right, a) : tmax(t->right, b);
}
return mx ? mx : (a>b ? tmax(t, a) : tmax(t, b));
}
node createNode(int c)
{
node x = (node)malloc(sizeof(struct bNode));
x->key = c;
x->left = NULL;
x->right = NULL;
x->p = NULL;
return x;
}
void insert(tree T, node x)
{
node y = NULL, t = T->root;
while(t)
{
y = t;
if(x->key>t->key)
t = t->right;
else
t = t->left;
}
if(!y)
T->root = x;
else if(x->key<y->key)
y->left = x;
else
y->right = x;
x->p = y;
}
node search(tree T, int k)
{
node t = T->root;
while(t && t->key!=k)
{
if(k>t->key)
t = t->right;
else
t = t->left;
}
return t;
}