-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
69 lines (61 loc) · 1.19 KB
/
100-binary_trees_ancestor.c
File metadata and controls
69 lines (61 loc) · 1.19 KB
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
#include "binary_trees.h"
/**
* depth - measure tree depth
* @tree: tree to measure
* Return: depth
*/
int depth(const binary_tree_t *tree)
{
int depth = 0;
if (!tree)
return (0);
while (tree->parent)
{
depth++;
tree = tree->parent;
}
return (depth);
}
/**
* binary_trees_ancestor - Finds the least common ancestor
* @first: first node
* @second: second node
* Return: least common ancestor
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
int first_depth, second_depth;
if (!first || !second)
return (NULL);
first_depth = depth(first);
second_depth = depth(second);
if (first_depth > second_depth)
{
while (first_depth != second_depth)
{
if (first->parent == second)
return (first->parent);
first = first->parent;
first_depth--;
}
}
else if (second_depth > first_depth)
{
while (second_depth != first_depth)
{
if (second->parent == first)
return (second->parent);
second = second->parent;
second_depth--;
}
}
while (second && first)
{
if (second->parent == first->parent)
return (first->parent);
second = second->parent;
first = first->parent;
}
return (NULL);
}