-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100-binary_trees_ancestor.c
52 lines (45 loc) · 1.15 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
#include "binary_trees.h"
/**
* binary_trees_ancestor - Finds the lowest common ancestor (LCA) of two nodes.
* @first: A pointer to the first node.
* @second: A pointer to the second node.
*
* Return: The lowest common ancestor (LCA) node of the two given nodes. NULL
* is returned when an ancestor is not found.
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
const binary_tree_t *temp;
binary_tree_t *first_ancestor, *second_ancestor;
if (first == NULL || second == NULL)
return (NULL);
temp = second;
while (temp != NULL)
{
if (temp == first)
return ((binary_tree_t *)first);
temp = temp->parent;
}
temp = first;
while (temp != NULL)
{
if (temp == second)
return ((binary_tree_t *)second);
temp = temp->parent;
}
first_ancestor = first->parent;
second_ancestor = second->parent;
while (first_ancestor != NULL)
{
while (second_ancestor != NULL)
{
if (first_ancestor == second_ancestor)
return (first_ancestor);
second_ancestor = second_ancestor->parent;
}
first_ancestor = first_ancestor->parent;
second_ancestor = second->parent;
}
return (NULL);
}