-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14-binary_tree_balance.c
41 lines (34 loc) · 1006 Bytes
/
14-binary_tree_balance.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
#include "binary_trees.h"
/**
* binary_tree_balance - measures the balance factor of a binary tree
* @tree: pointer to the root node of the tree to measure the balance factor
*
* Return: the balance factor
* 0 if tree is NULL
*/
int binary_tree_balance(const binary_tree_t *tree)
{
int height_l, height_r;
if (!tree)
return (0);
height_l = tree->left ? (int)binary_tree_height(tree->left) : -1;
height_r = tree->right ? (int)binary_tree_height(tree->right) : -1;
return (height_l - height_r);
}
/**
* binary_tree_height - measures the height of a binary tree
* @tree: tree to measure the height of
*
* Return: height of the tree
* 0 if tree is NULL
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t height_l = 0;
size_t height_r = 0;
if (!tree)
return (0);
height_l = tree->left ? 1 + binary_tree_height(tree->left) : 0;
height_r = tree->right ? 1 + binary_tree_height(tree->right) : 0;
return (height_l > height_r ? height_l : height_r);
}