-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path14-binary_tree_balance.c
More file actions
executable file
·42 lines (34 loc) · 1.04 KB
/
14-binary_tree_balance.c
File metadata and controls
executable file
·42 lines (34 loc) · 1.04 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
#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: Balance factor or 0 if tree is NULL
*/
int binary_tree_balance(const binary_tree_t *tree)
{
int left_height, right_height;
if (!tree)
return (0);
left_height = tree->left ? (int)binary_tree_height(tree->left) : -1;
right_height = tree->right ? (int)binary_tree_height(tree->right) : -1;
return (left_height - right_height);
}
/**
* binary_tree_height - Measures the height of a binary tree
*
* @tree: Pointer to the root node of the tree to measure the height
*
* Return: Height of the binary tree
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_height = 0;
size_t right_height = 0;
if (tree == NULL)
return (0);
left_height = tree->left ? 1 + binary_tree_height(tree->left) : 0;
right_height = tree->right ? 1 + binary_tree_height(tree->right) : 0;
return (left_height > right_height ? left_height : right_height);
}