-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-binary_trees_ancestor.c
52 lines (46 loc) · 1015 Bytes
/
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_tree_depth - Measures the depth of a node in a binary tree.
*
* @tree: A pointer to the node to measure the depth.
*
* Return: 0 if tree is NULL.
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (binary_tree_depth(tree->parent) + 1);
}
/**
* 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.
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
int dp1 = binary_tree_depth(first);
int dp2 = binary_tree_depth(second);
while (dp1 != dp2)
{
if (dp1 > dp2)
{
first = first->parent;
dp1--;
}
else
{
second = second->parent;
dp2--;
}
}
while (second != first)
{
second = second->parent;
first = first->parent;
}
return ((binary_tree_t *)second);
}