-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
55 lines (44 loc) · 1.33 KB
/
100-binary_trees_ancestor.c
File metadata and controls
55 lines (44 loc) · 1.33 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
#include "binary_trees.h"
int binary_tree_is_descendant(const binary_tree_t *node, const
binary_tree_t *ancestor);
/**
* binary_trees_ancestor - Find the lowest common ancestor of two nodes
* @first: Pointer to the first node
* @second: Pointer to the second node
*
* Return: Pointer to the lowest common ancestor node or NULL
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first, const
binary_tree_t *second)
{
binary_tree_t *ancestor;
if (!first || !second)
return (NULL);
if (first == second)
return ((binary_tree_t *)first);
if (binary_tree_is_descendant(second, first))
return ((binary_tree_t *)first);
if (binary_tree_is_descendant(first, second))
return ((binary_tree_t *)second);
ancestor = binary_trees_ancestor(first->parent, second);
if (!ancestor)
return (binary_trees_ancestor(first, second->parent));
return (ancestor);
}
/**
* binary_tree_is_descendant - Check if one node is a descendant of another
* @node: Potential descendant
* @ancestor: Potential ancestor
*
* Return: 1 if the first node is a descendant
* of the second, 0 otherwise
*/
int binary_tree_is_descendant(const binary_tree_t *node,
const binary_tree_t *ancestor)
{
if (node == NULL || ancestor == NULL)
return (0);
if (node == ancestor)
return (1);
return (binary_tree_is_descendant(node->parent, ancestor));
}