-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
66 lines (60 loc) · 1.45 KB
/
100-binary_trees_ancestor.c
File metadata and controls
66 lines (60 loc) · 1.45 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
#include "binary_trees.h"
/**
* binary_trees_ancestor - Finds the lowest common ancestor of two nodes.
*
* @first: A pointer to the first node.
* @second: A pointer to the second node.
*
* Return: A pointer to the lowest common ancestor node of the two given nodes.
* If no common ancestor was found, your function must return NULL.
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
if (!first || !second)
return (NULL);
const binary_tree_t *f = first;
const binary_tree_t *s = second;
while (f && s)
{
if (f == s)
return ((binary_tree_t *)f);
/* Check if one node is an ancestor of the other */
if (f->parent)
{
if (is_descendant(f->parent, second))
return ((binary_tree_t *)f->parent);
f = f->parent;
}
else if (s->parent)
{
if (is_descendant(s->parent, first))
return ((binary_tree_t *)s->parent);
s = s->parent;
}
else
{
/* No more parents to explore, no common ancestor */
return (NULL);
}
}
return (NULL);
}
/**
* is_descendant - Helper function to check
* if a node is a descendant of another
* @parent: A pointer to the parent node.
* @node: A pointer to the node to check.
*
* Return: true if node is a descendant of parent, otherwise false.
*/
bool is_descendant(const binary_tree_t *parent, const binary_tree_t *node)
{
while (node)
{
if (node == parent)
return (true);
node = node->parent;
}
return (false);
}