-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14-binary_tree_balance.c
More file actions
57 lines (45 loc) · 1.03 KB
/
14-binary_tree_balance.c
File metadata and controls
57 lines (45 loc) · 1.03 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
#include "binary_trees.h"
/**
* recursive_height - measures the height of a binary tree
* @tree: tree root
*
* Return: height
*/
size_t recursive_height(const binary_tree_t *tree)
{
size_t left = 0;
size_t right = 0;
if (tree == NULL)
return (0);
left = recursive_height(tree->left);
right = recursive_height(tree->right);
if (left > right)
return (left + 1);
return (right + 1);
}
/**
* binary_tree_height - calls recursive_height to return the height
* of a binary tree
* @tree: tree root
*
* Return: height of the tree or 0 if tree is NULL;
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
if (tree == NULL)
return (-1);
return (recursive_height(tree) - 1);
}
/**
* binary_tree_balance - calls recursive_balance to return the balance
* of a binary tree
* @tree: tree root
*
* Return: balance factor of the tree or 0 if tree is NULL;
*/
int binary_tree_balance(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (binary_tree_height(tree->left) - binary_tree_height(tree->right));
}