-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-binary_trees_ancestor.c
64 lines (49 loc) · 1 KB
/
100-binary_trees_ancestor.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
#include "binary_trees.h"
/**
* binary_tree_depth - measures depth
* @tree: tree
* Return: depth or NULL
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
size_t depth = 0;
while (tree != NULL)
{
depth++;
tree = tree->parent;
}
return (depth);
}
/**
* binary_trees_ancestor - finds the lowest common ancestor of two nodes
* @first: first node
* @second: second node
* Return: lowest common ancestor or NULL
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
size_t d_first, d_second;
if (first == NULL || second == NULL)
return (NULL);
d_first = binary_tree_depth(first);
d_second = binary_tree_depth(second);
while (d_first > d_second)
{
first = first->parent;
d_first--;
}
while (d_second > d_first)
{
second = second->parent;
d_second--;
}
while (first != NULL && second != NULL)
{
if (first == second)
return ((binary_tree_t *)first);
first = first->parent;
second = second->parent;
}
return (NULL);
}