-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path14-binary_tree_balance.c
More file actions
51 lines (43 loc) · 1.03 KB
/
14-binary_tree_balance.c
File metadata and controls
51 lines (43 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
#include "binary_trees.h"
/**
* binary_tree_height - measures the height of a binary tree
*
* @tree: node type binary_tree_t
* Return: height of a binary tree
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_height = 0, right_height = 0;
if (!tree)
return (0);
if (tree->right)
right_height = 1 + binary_tree_height(tree->right);
else
right_height = 0;
if (tree->left)
left_height = 1 + binary_tree_height(tree->left);
else
left_height = 0;
return ((left_height > right_height) ? left_height : right_height);
}
/**
* binary_tree_balance - measures the height of a binary tree
*
* @tree: node type binary_tree_t
* Return: balance factor of a binary tree
*/
int binary_tree_balance(const binary_tree_t *tree)
{
int height_left = 0, height_right = 0;
if (!tree)
return (0);
if (tree->left)
height_left = binary_tree_height(tree->left);
else
height_left = -1;
if (tree->right)
height_right = binary_tree_height(tree->right);
else
height_right = -1;
return (height_left - height_right);
}