-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
executable file
·58 lines (52 loc) · 1.26 KB
/
Copy path100-binary_trees_ancestor.c
File metadata and controls
executable file
·58 lines (52 loc) · 1.26 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
#include "binary_trees.h"
size_t depth(const binary_tree_t *tree);
/**
*depth - measures the depth of a node in a binary tree
*@tree: Pointer to the first node in the tree
*Return: An integer representing the depth
*/
size_t depth(const binary_tree_t *tree)
{
if (!tree)
return (0);
if (!tree->parent)
return (0);
return (1 + depth(tree->parent));
}
/**
* binary_trees_ancestor - Finds the sibling of a node.
* @first: Pointer to the first node.
* @second: Pointer to the second node.
* Return: Pointer to the lowest common ancestor node of the two given nodes.
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
binary_tree_t *senior, *junior, *h;
size_t f, s;
if (!first || !second)
return (NULL);
if (first == second)
return ((binary_tree_t *)first);
f = depth(first);
s = depth(second);
if ((f == s) && first->parent == second->parent)
{
return (first->parent);
}
senior = (f <= s) ? (binary_tree_t *)first : (binary_tree_t *)second;
junior = (f <= s) ? (binary_tree_t *)second : (binary_tree_t *)first;
h = junior;
while (senior)
{
while (junior)
{
if (junior == senior)
return (junior);
junior = junior->parent;
}
junior = h;
senior = senior->parent;
}
return (NULL);
}