-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
59 lines (53 loc) · 1.21 KB
/
100-binary_trees_ancestor.c
File metadata and controls
59 lines (53 loc) · 1.21 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
#include "binary_trees.h"
/**
* binary_tree_ancestor - finds the uncle 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, 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)
{
int f_depth, s_depth;
if (first == NULL || second == NULL)
return (NULL);
f_depth = binary_tree_depth(first);
s_depth = binary_tree_depth(second);
while (s_depth > f_depth)
{
second = second->parent;
s_depth--;
}
while (f_depth > f_depth)
{
first = first->parent;
s_depth--;
}
while (first != NULL && second != NULL)
{
if (first == second)
return ((binary_tree_t *)first);
first = first->parent;
second = second->parent;
}
return (NULL);
}
/**
* binary_tree_depth - measures the depth of a node in a binary tree
* @tree: Pointer to the root node of the tree
* Return: If tree is NULL return 0
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
size_t depth = 0;
if (tree == NULL)
return (0);
while (tree->parent != NULL)
{
depth++;
tree = tree->parent;
}
return (depth);
}