forked from retired337in/binary_trees
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path120-binary_tree_is_avl.c
51 lines (41 loc) · 1.07 KB
/
120-binary_tree_is_avl.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
42
43
44
45
46
47
48
49
50
51
#include "binary_trees.h"
/**
* binary_tree_height - Measure the height of a binary tree
*
* @tree: Pointer to the root node of the tree to measure
*
* Return: The height of the tree starting at the given node
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_height, right_height;
if (!tree)
{
return (0);
}
left_height = binary_tree_height(tree->left);
right_height = binary_tree_height(tree->right);
return (1 + (left_height > right_height ?
left_height : right_height));
}
/**
* binary_tree_is_avl - Check if a binary tree is a valid AVL Tree
*
* @tree: Pointer to the root node of the tree to check
*
* Return: 1 if tree is a valid AVL Tree, 0 otherwise
*/
int binary_tree_is_avl(const binary_tree_t *tree)
{
if (tree == NULL)
return (1);
int left_height;
int right_height;
left_height = binary_tree_height(tree->left);
right_height = binary_tree_height(tree->right);
if (abs(left_height - right_height) > 1)
return (0);
if (!binary_tree_is_avl(tree->left) || !binary_tree_is_avl(tree->right))
return (0);
return (1);
}