-
Notifications
You must be signed in to change notification settings - Fork 0
/
120-binary_tree_is_avl.c
executable file
·65 lines (59 loc) · 1.65 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "binary_trees.h"
int binary_tree_is_avl(const binary_tree_t *tree);
int is_avl_helper(const binary_tree_t *tree, int lo, int hi);
size_t height(const binary_tree_t *tree);
/**
* binary_tree_is_avl - Checks if a binary tree is a valid AVL Tree.
*
* @tree: A pointer to the root node of the tree to check.
*
* Return: 1 if tree is a valid AVL Tree, and 0 otherwise.
*/
int binary_tree_is_avl(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (is_avl_helper(tree, INT_MIN, INT_MAX));
}
/**
* is_avl_helper - Checks if a binary tree is a valid AVL tree.
* @tree: A pointer to the root node of the tree to check.
* @lo: The value of the smallest node visited thus far.
* @hi: The value of the largest node visited this far.
*
* Return: If the tree is a valid AVL tree, 1, otherwise, 0.
*/
int is_avl_helper(const binary_tree_t *tree, int lo, int hi)
{
size_t lhgt, rhgt, diff;
if (tree != NULL)
{
if (tree->n < lo || tree->n > hi)
return (0);
lhgt = height(tree->left);
rhgt = height(tree->right);
diff = lhgt > rhgt ? lhgt - rhgt : rhgt - lhgt;
if (diff > 1)
return (0);
return (is_avl_helper(tree->left, lo, tree->n - 1) &&
is_avl_helper(tree->right, tree->n + 1, hi));
}
return (1);
}
/**
* height - Measures the height of a binary tree.
* @tree: A pointer to the root node of the tree to measure the height.
*
* Return: If tree is NULL, your function must return 0, else return height.
*/
size_t height(const binary_tree_t *tree)
{
if (tree)
{
size_t l = 0, r = 0;
l = tree->left ? 1 + height(tree->left) : 1;
r = tree->right ? 1 + height(tree->right) : 1;
return ((l > r) ? l : r);
}
return (0);
}