-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path100-binary_trees_ancestor.c
More file actions
58 lines (46 loc) · 1.3 KB
/
100-binary_trees_ancestor.c
File metadata and controls
58 lines (46 loc) · 1.3 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"
/**
* recursive_depth - measures the depth of a node in a binary tree
* @tree: tree root
*
* Return: depth of a node in a binary tree
*/
size_t recursive_depth(const binary_tree_t *tree)
{
if (tree == NULL)
return (-1);
return (recursive_depth(tree->parent) + 1);
}
/**
* binary_tree_depth - calls recursive_depth to return the depth
* of a node in a binary tree
* @tree: tree root
*
* Return: depth of the tree or 0 if tree is NULL;
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (recursive_depth(tree));
}
/**
* binary_tree_uncle - finds 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
*/
binary_tree_t *binary_trees_ancestor(const binary_tree_t *first,
const binary_tree_t *second)
{
if (first == NULL || second == NULL)
return (NULL);
if (first == second)
return ((binary_tree_t *)first);
if (binary_tree_depth(first) > binary_tree_depth(second))
return (binary_trees_ancestor(first->parent, second));
if (binary_tree_depth(first) < binary_tree_depth(second))
return (binary_trees_ancestor(first, second->parent));
return (binary_trees_ancestor(first->parent, second->parent));
}